问题
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]
}
来源:https://stackoverflow.com/questions/36064086/swift-decode-array-custom-class-memory-leak