ios - 在应用程序启动之间保留数据

标签 ios swift

我有一个类可以在我的应用程序中处理一个简单的笔记创建者。目前,笔记是使用自定义笔记对象数组存储的。如何在应用程序关闭时保存此数组的内容并在应用程序重新打开时再次加载它们?我试过 NSUserDefaults,但我不知道如何保存数组,因为它不仅仅是由字符串组成。

代码:

注意.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"),]

最佳答案

对此有不同的方法。

NS编码

最简单的是采用NSCoding,让Note继承NSObject,使用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 框架 - 它的用法超出了 SO 答案的范围。

延伸阅读

关于ios - 在应用程序启动之间保留数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35516769/

相关文章:

swift - 以编程方式调用 View 后选项卡栏消失

ios - 有没有办法获取 UIImage 文件名?

ios - 无论是通过手刹还是通过ffmpeg,我都无法获得1334x750的分辨率

swift - 解决引发 SIGABRT 错误的核心数据关系

ios - 如何删除 uicollectionview top padding swift 4 iOS 11?

swift - tableView下添加TapGesture查看

ios - 在 iOS 中打开或关闭推送通知检查

ios - 使用 AVPlayer 获取 AirPlay 设备的名称

javascript - "Run JavaScript on Web Page"的 iOS 12 快捷方式设置问题

ios - CSStickyHeaderFlowLayout swift 接收器没有带标识符的 segue