Swift Decode Array Custom Class Memory Leak

2019-07-26 15:04发布

问题:

I'm saving my app config using NSCoding and am getting a leak in Instruments when using DecodeWithKey.

Settings has a property stsSettings

stsSettings = (aDecoder.decodeObjectForKey("stsSettings") as! StsSettings)

stsSettings has a property array of StsVariables

stsVariables = (aDecoder.decodeObjectForKey("stsVariables") as! [StsVariable])

Leaked Object # Address Size Responsible Library Responsible Frame StsVariable 1 0x7fe182d494f0 192 Bytes Foundation _decodeObjectBinary

Settings also has a property conversions which is an array of Conversion objects and this doesn't leak, so I can't work out what's going on.

回答1:

I experienced a memory leak in a similar situation. I resolved the issue by assigning the decoded array to a local variable and copy the elements to the property. However, I don't know why the memory leak was there in the first place.

let variables = (aDecoder.decodeObjectForKey("stsVariables") as! [StsVariable])
stsVariables = [StsVariable]()
for variable in variables {
    stsVariables += [variable]
}