为什么我的Swift 3编码会丢失?

时间:2017-04-25 03:45:53

标签: swift decode encode

我有一个Swift类,它有一些" var" s是原始整数值,有些是原始整数值的数组,或者像CMTime这样的结构数组。当我在对象上执行NSKeyedArchiver.archiveRootObject时,如果我将编码限制为整数值,[CMTime]和最小的整数数组,一切正常。 (我可以编码,然后解码,并验证内容是否相等。) 令人费解的是,对调试器理解的[UInt16]进行编码的成员少于100M,导致应用程序在编码期间的内存分配增加到4Gb,然后是8Gb,然后是12Gb(我点击STOP)。 我使用coder.encode(aSwiftArray,forKey:" aKey")是否有问题,有时可以使用,但有些不是吗?

typealias WordSize = UInt16
class PixelHistogram :NSObject, NSCoding {
    var pixelCount:Int = 0
    var timeAtFrame: [CMTime] = [] // CMTime for each frame
    var pixelVsDelta: [UInt] = [] // 256x256 histogram of pixel vs DeltaPixel
    var histPixel:[WordSize] = [] // histogram of Y at each pixel [pixelCount][256]
}
// Initializing the various arrays...
histPixel = [WordSize](repeating: 0, count: 256*pixelCount)
pixelVsDelta = [UInt](repeating: 0, count: 256*256)

required convenience init?(coder aDecoder:NSCoder){
self.init()
timeAtFrame = aDecoder.decodeObject(forKey:Slot.timeAtFrame.rawValue ) as! [CMTime]
pixelVsDelta = aDecoder.decodeObject(forKey:Slot.pixelVsDelta.rawValue) as! [UInt]
    func encode(with coder:NSCoder)
    coder.encode(timeAtFrame, forKey: Slot.timeAtFrame.rawValue)        
    coder.encode(pixelVsDelta, forKey: Slot.pixelVsDelta.rawValue)
    }           

1 个答案:

答案 0 :(得分:0)

编码histPixel时内存失控的一个可能答案是encodeObject正在将数组中的每个UInt16值转换为NSNumber。我曾假设编码只是在幕后使用encodeBytes。