swift - 如何在 Swift 中编写 initwithcoder?

标签 swift initwithcoder

我是 swift 的新手,我对 swift 中的 initwithcoder 有疑问。

我有 UserItem 类,我需要它来保存用户登录。

在 objective-c 中是这样的

 - (id)initWithCoder:(NSCoder *)decoder{
    if (self = [super init]){
        self.username = [decoder decodeObjectForKey:@"username"];
    }
    return self;
}

很快我就这样尝试

override init() {
   super.init()
}    

required init(coder decoder: NSCoder!) {

   self.username = (decoder.decodeObjectForKey("username")?.stringValue)!

   super.init(coder: decoder)
}

但是如果像上面那样,我会在代码上出错

super.init(coder: decoder)

错误信息是“调用中有额外的参数‘coder’”

我想不通了,所以我试试这个代码,

convenience init(decoder: NSCoder) {
   self.init()

   self.username = (decoder.decodeObjectForKey("username")?.stringValue)!
}

但是,得到错误

.UserItem initWithCoder:]: unrecognized selector sent to instance 0x7fd4714ce010

我该怎么办?之前感谢您的帮助。

最佳答案

我过去曾与 NSCoding(用于存档和取消存档对象的协议(protocol))作斗争,我看到您正在经历同样的痛苦。希望这能减轻一点:

class UserItem: NSObject, NSCoding {
    var username: String
    var anInt: Int

    init(username: String, anInt: Int) {
        self.username = username
        self.anInt = anInt
    }

    required init?(coder aDecoder: NSCoder) {
        // super.init(coder:) is optional, see notes below
        self.username = aDecoder.decodeObjectForKey("username") as! String
        self.anInt = aDecoder.decodeIntegerForKey("anInt")
    }

    func encodeWithCoder(aCoder: NSCoder) {
        // super.encodeWithCoder(aCoder) is optional, see notes below
        aCoder.encodeObject(self.username, forKey: "username")
        aCoder.encodeInteger(self.anInt, forKey: "anInt")
    }

    // Provide some debug info
    override var description: String {
        get {
            return ("\(self.username), \(self.anInt)")
        }
    }
}

// Original object
let a = UserItem(username: "michael", anInt: 42)

// Serialized data
let data = NSKeyedArchiver.archivedDataWithRootObject(a)

// Unarchived from data
let b = NSKeyedUnarchiver.unarchiveObjectWithData(data)!

print(a)
print(b)

重要的是匹配encodeWithCoder(aCoder:)(归档函数)和init(coder:)(unarchive函数)中的键和数据类型函数)。

让初学者困惑的是如何处理父类(super class)。如果父类(super class)本身符合 NSCoding,您应该只在上面的两个函数中包含父类(super class)。 NSObject 本身不提供。这个想法是每个类都知道自己的属性,其中一些是私有(private)的。如果父类(super class)无法存档/取消存档,则无需调用它们。

关于swift - 如何在 Swift 中编写 initwithcoder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33990677/

相关文章:

swift iOS 7 替换时间和距离计数器

ios - 如何在 ViewController 顶部设置标题

swift - 如何禁用 macOS Catalyst 应用程序中的 "Show Tab Bar"选项

ios - 具有 1 个数据源的 tableview 单元格内的 Collectionview

arrays - 在swift中过滤元素出现次数最多的数组

ios - 在 initWithCoder : 上查看 1000x1000

objective-c - Objective-C - 自定义 View 和实现 init 方法?

xcode - 使用 Swift 子类化 UIView,在 Nib 中使用

ios - super initWIthCoder 返回父类型?