简体   繁体   English

使用NSCoder Swift编码数组

[英]Coding array with NSCoder Swift

I'm trying to implement the NSCoder, but am currently facing a stubborn issue. 我正在尝试实现NSCoder,但目前面临一个顽固的问题。 My goal is to save the array of strings via NSCoder to a local file and load it when the app opens next time. 我的目标是通过NSCoder将字符串数组保存到本地文件,并在下次打开应用程序时加载它。

Here is the class i've created, but i'm not sure how i should handle the init and encoder functions: 这是我创建的类,但是我不确定如何处理init和encoder函数:

class MyObject: NSObject, NSCoding {

var storyPoints: [String] = []

init(storyPoints : [String]) {
    self.storePoints = storePoints
}


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

???

}

func encodeWithCoder(coder: NSCoder) {
???
}

} }

Moreover, how do i access it in my view controller? 此外,如何在视图控制器中访问它? where should i declare a path for saving the NSCoder? 我应该在哪里声明保存NSCoder的路径? It's not really clear enough. 还不够清楚。

Looking forward to any advices. 期待任何建议。

Thank you. 谢谢。

Here is an implementation and a playground example that saves the object to the /tmp directory. 这是将对象保存到/ tmp目录的实现和游乐场示例。 The init(coder:) function overrides NSObject's so is required and since it is not a designated initializer it must be marked as convenience . init(coder:)函数将覆盖NSObject的功能,因此这是required并且由于它不是指定的初始化程序,因此必须将其标记为convenience Also because init(coder:) is a convenience initializer, it can not call super.init() . 另外,因为init(coder:)是便捷的初始化程序,所以它无法调用super.init()

To directly answer your question about archiving an array, just type cast the result from decoderObjectForKey(_:) . 要直接回答有关归档数组的问题,只需将类型从decoderObjectForKey(_:)decoderObjectForKey(_:)类型。 Check the NSCoding documentation for information and API's to code/decode. 检查NSCoding文档以获取信息和API进行编码/解码。 There is a lot there. 那里有很多东西。

import Cocoa

class MyObject: NSObject, NSCoding {

  var storyPoints: [String] = []

  init(storyPoints : [String]) {
    self.storyPoints = storyPoints
  }

  convenience required init(coder decoder: NSCoder) {
    let storyPoints = decoder.decodeObjectForKey("storypoints") as! [String]
    self.init(storyPoints: storyPoints)
  }

  func encodeWithCoder(coder: NSCoder) {
    coder.encodeObject(storyPoints, forKey: "storypoints")
  }
}

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM