简体   繁体   中英

Coding array with NSCoder Swift

I'm trying to implement the NSCoder, but am currently facing a stubborn issue. My goal is to save the array of strings via NSCoder to a local file and load it when the app opens next time.

Here is the class i've created, but i'm not sure how i should handle the init and encoder functions:

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? 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. The init(coder:) function overrides NSObject's so is required and since it is not a designated initializer it must be marked as convenience . Also because init(coder:) is a convenience initializer, it can not call super.init() .

To directly answer your question about archiving an array, just type cast the result from decoderObjectForKey(_:) . Check the NSCoding documentation for information and API's to code/decode. 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")
  }
}

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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