Swift中的自定义类存档

时间:2015-02-03 09:44:58

标签: ios swift nskeyedarchiver nskeyedunarchiver

我想在swift中存档和取消归档自定义对象,如下所示:

class Line : NSObject, NSCoding  {

    var start : CGPoint


    init(start _start: CGPoint) {
        start = _start
    }

    required init(coder aDecoder: NSCoder) {
        // 1 - compile time error
        self.start = aDecoder.decodeObjectForKey("start") as CGPoint
    }

    override init() {
    }

    func encodeWithCoder(aCoder: NSCoder) {
        // 2 - compile time error
        aCoder.encodeObject(start, forKey: "start")
    }
}

1.编译时错误是: 输入' CGPoint'不符合协议' AnyObject'

2.编译时错误是: 额外的争论' forKey'在电话中

如何归档和取消归档CGPoint,我知道CGPoint是一个惊天动地,这是问题,但如何解决?

提前感谢。

3 个答案:

答案 0 :(得分:5)

您可以使用以下方式归档/取消归档CGPoint:

encodeCGPoint:forKey:

decodeCGPointForKey:

此处提供更多信息:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCoder_Class/index.html#//apple_ref/occ/instm/NSCoder/encodeCGPoint:forKey:

答案 1 :(得分:1)

可以将CGPoint转换为NSValue。

func encodeWithCoder(aCoder: NSCoder) {
    var cgPointAsObject:NSValue = NSValue(CGPoint: start)
    aCoder.encodeObject(cgPointAsObject, forKey: "start")
}

类似地,反向过程在解码时将NSValue转换为CGpoint。

答案 2 :(得分:0)

swift3中,有一些func已更改,可执行以下操作:

class UserModel: NSObject,NSCoding {

var username:String = ""
var password: Int = 0

required init(coder aDecoder: NSCoder) {
    super.init()

}

override init() {

}

func encode(with aCoder: NSCoder) {

    }

}