ios – 什么是在应用程序终止之前存储(持久化)结构数组的最有效方法?

编程语言 – 迅捷.

我创建了一个结构来存储与我的应用程序相关的所有相关信息,如下所示.此外,我正在创建一个类型为wordstruct的数组,并使用3000个条目填充它.

struct wordStruct{
    var wordd:NSString
    var meaning: [NSString]
    var sentance: String
    var syn: [String]
    var seen:Int
    var set: Int
    var HF: Int
}

在尝试了我能想到的多种方法之后,我无法存储(持久化)数据(即结构数组).
我已经尝试过NSUserDefault,Plist和NSCoding方法(我可能做错了.)
存储结构数组的最有效方法是什么?
可以将数组写入文件吗?

最佳答案 结构不能符合NSCoding,因为NSCoding是一种类协议.如果您想使用NSCoding来保持模型(这通常是最直接的方法),您必须将模型重新声明为符合NSCoding的NSObject.

以下是基于您提供的代码段如何实现它的示例:

class Word: NSObject, NSCoding {

    var word: NSString!
    var meaning: [NSString]!
    var sentence: String!
    var syn: [String]!
    var seen:Int!
    var set: Int!
    var HF: Int!
    // specify how your model will be decoded:
    required convenience init(coder decoder: NSCoder) {
        self.init()
        self.word = decoder.decodeObjectForKey("word") as! String
        self.meaning = decoder.decodeObjectForKey("meaning") as! [String]
        self.sentence = decoder.decodeObjectForKey("sentence") as! String
        self.syn = decoder.decodeObjectForKey("syn") as! [String]
        self.seen = decoder.decodeIntegerForKey("seen")
        self.set = decoder.decodeIntegerForKey("set")
        self.HF = decoder.decodeIntegerForKey("HF")
    }
    // specify how your model will be encoded
    func encodeWithCoder(coder: NSCoder) {
        coder.encodeObject(word, forKey: "word")
        coder.encodeObject(meaning, forKey: "meaning")
        coder.encodeObject(sentence, forKey: "sentence")
        coder.encodeObject(syn, forKey: "syn")
        coder.encodeInteger(seen, forKey: "seen")
        coder.encodeInteger(set, forKey: "set")
        coder.encodeInteger(HF, forKey: "HF")
    }
}

// an example word:
let example = Word()
example.word = "example"
example.meaning = ["abstractions", "generalizations", "use cases"]
example.sentence = "here is how you can implement NSCoding"
example.syn = ["what", "is", "a", "syn"]
example.seen = 1
example.set = 2
example.HF = 3

// persist the example to NSUserDefaults
let data = NSKeyedArchiver.archivedDataWithRootObject(example)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "example")

// load the saved example from NSUserDefaults 
if let data = NSUserDefaults.standardUserDefaults().objectForKey("example") as? NSData {
    if let example = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? Word {
        example.meaning // ["abstractions", "generalizations", "use cases"]
        example.set // 2
        example.seen // 1
        example.word // "example"
    }
}

为了进一步阅读,Matt Thompson在这里有一个很好的帖子:
http://nshipster.com/nscoding/

阅读官方文档永远不会伤害:
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Protocols/NSCoding_Protocol/index.html

点赞