在应用启动之间保留数据

我有一个类在我的应用程序中处理一个简单的笔记创建者。 目前,使用一组自定义Note对象存储注释。 当应用程序关闭时如何保存此数组的内容,并在重新打开应用程序时再次加载它们? 我已经尝试了NSUserDefaults,但我无法弄清楚如何保存数组,因为它不仅仅是由字符串组成。

码:

Note.swift

class Note { var contents: String // an automatically generated note title, based on the first line of the note var title: String { // split into lines let lines = contents.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as [String] // return the first return lines[0] } init(text: String) { contents = text } } var notes = [ Note(text: "Contents of note"),] 

有不同的方法。

NSCoding

最简单的方法是采用NSCoding ,让NoteNSObjectinheritance并使用NSKeyedArchiverNSKeyedUnarchiver来写入应用程序沙箱中的文件。

这是一个简单的例子:

 final class Feedback : NSObject, NSCoding { private static let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let content : String let entry : EntryId let positive : Bool let date : NSDate init(content: String, entry: EntryId, positive : Bool, date :NSDate = NSDate()) { self.content = content self.entry = entry self.positive = positive self.date = date super.init() } @objc init?(coder: NSCoder) { if let c = coder.decodeObjectForKey("content") as? String, let d = coder.decodeObjectForKey("date") as? NSDate { let e = coder.decodeInt32ForKey("entry") let p = coder.decodeBoolForKey("positive") self.content = c self.entry = e self.positive = p self.date = d } else { content = "" entry = -1 positive = false date = NSDate() } super.init() if self.entry == -1 { return nil } } @objc func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeBool(self.positive, forKey: "positive") aCoder.encodeInt32(self.entry, forKey: "entry") aCoder.encodeObject(content, forKey: "content") aCoder.encodeObject(date, forKey: "date") } static func feedbackForEntry(entry: EntryId) -> Feedback? { let path = Feedback.documentsPath.stringByAppendingString("/\(entry).feedbackData") if let success = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? Feedback { return success } else { return nil } } func save() { let path = Feedback.documentsPath.stringByAppendingString("/\(entry).feedbackData") let s = NSKeyedArchiver.archiveRootObject(self, toFile: path) if !s { debugPrint("Warning: did not save a Feedback for \(self.entry): \"\(self.content)\"") } } } 

核心数据

更有效但更复杂的解决方案是使用Core Data,即Apple的ORM-Framework–其使用范围超出了SO答案的范围。

进一步阅读

  • NSHipster文章
  • 归档编程指南
  • 核心数据编程指南