You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xcode:如何从模拟器访问基于NSCoder存储的持久化数据?

使用NSCoder实现UserNotification对象的持久化

首先,你已经写好了遵循NSCoding协议的UserNotification类,这个类可以把对象序列化为可存储的格式,下面是完整的类代码:

class UserNotification: NSObject, NSCoding {
    var message: String!
    
    init(message: String) {
        self.message = message
    }
    
    required convenience init(coder aDecoder: NSCoder) {
        let message = aDecoder.decodeObject(forKey: "message") as! String
        self.init(message: message)
    }
    
    func encode(with aCoder: NSCoder) {
        aCoder.encode(message, forKey: "message")
    }
}

接下来我帮你补全保存到UserDefaults和从UserDefaults加载的完整逻辑:

1. 保存对象到UserDefaults

要把UserNotification对象存入UserDefaults,需要先将它归档成Data类型:

// 创建示例通知对象
let newNotification = UserNotification(message: "您有一条未读消息")

// 归档对象为Data格式
if let data = try? NSKeyedArchiver.archivedData(withRootObject: newNotification, requiringSecureCoding: false) {
    // 存储到UserDefaults
    UserDefaults.standard.set(data, forKey: "SavedUserNotification")
}

2. 从UserDefaults加载对象

取出存储的Data后,再解档回UserNotification对象即可使用:

// 从UserDefaults获取存储的Data
if let savedData = UserDefaults.standard.data(forKey: "SavedUserNotification"),
   let loadedNotification = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(savedData) as? UserNotification {
    // 成功加载,可使用对象属性
    print(loadedNotification.message) // 输出: 您有一条未读消息
}

一些实用优化提示

  • 你代码里用了as! String强制解包,如果存储的message为nil或类型不匹配会直接崩溃,建议改成可选绑定提升安全性:
    required convenience init(coder aDecoder: NSCoder) {
        guard let message = aDecoder.decodeObject(forKey: "message") as? String else {
            self.init(message: "") // 也可根据业务需求处理nil场景
            return
        }
        self.init(message: message)
    }
    
  • 如果需要存储多个UserNotification对象,可以把它们放到数组中再归档存储,加载时解档为[UserNotification]类型即可。
  • iOS 12及以上版本推荐开启安全编码,将requiringSecureCoding设为true,同时让类遵循NSSecureCoding协议。

内容的提问来源于stack exchange,提问作者drante

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:43:45