使用 NSCoding 将自定义 Swift 类保存到 UserDefaults [英] Saving custom Swift class with NSCoding to UserDefaults

查看:80
本文介绍了使用 NSCoding 将自定义 Swift 类保存到 UserDefaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试将自定义 Swift 类保存到 NSUserDefaults.这是我的 Playground 中的代码:

I am currently trying to save a custom Swift class to NSUserDefaults. Here is the code from my Playground:

import Foundation

class Blog : NSObject, NSCoding {

    var blogName: String?

    override init() {}

    required init(coder aDecoder: NSCoder) {
        if let blogName = aDecoder.decodeObjectForKey("blogName") as? String {
            self.blogName = blogName
        }
    }

    func encodeWithCoder(aCoder: NSCoder) {
        if let blogName = self.blogName {
            aCoder.encodeObject(blogName, forKey: "blogName")
        }
    }

}

var blog = Blog()
blog.blogName = "My Blog"

let ud = NSUserDefaults.standardUserDefaults()    
ud.setObject(blog, forKey: "blog")

当我运行代码时,出现以下错误

When I run the code, I get the following error

执行被中断,原因:信号SIGABRT.

Execution was interrupted, reason: signal SIGABRT.

在最后一行 (ud.setObject...)

in the last line (ud.setObject...)

在带有消息的应用中时,同样的代码也会崩溃

The same code also crashes when in an app with the message

"属性列表对格式无效:200(属性列表不能包含'CFType') 类型的对象"

"Property list invalid for format: 200 (property lists cannot contain objects of type 'CFType')"

有人可以帮忙吗?我在 Maverick 上使用 Xcode 6.0.1.谢谢.

Can anybody help? I am using Xcode 6.0.1 on Maverick. Thanks.

推荐答案

正如@dan-beaulieu 建议我回答我自己的问题:

As @dan-beaulieu suggested I answer my own question:

这是现在的工作代码:

注意:代码在 Playgrounds 中工作不需要对类名进行重组.

Note: Demangling of the class name was not necessary for the code to work in Playgrounds.

import Foundation

class Blog : NSObject, NSCoding {

    var blogName: String?

    override init() {}

    required init(coder aDecoder: NSCoder) {
        if let blogName = aDecoder.decodeObjectForKey("blogName") as? String {
            self.blogName = blogName
        }
    }

    func encodeWithCoder(aCoder: NSCoder) {
        if let blogName = self.blogName {
            aCoder.encodeObject(blogName, forKey: "blogName")
        }
    }

}

let ud = NSUserDefaults.standardUserDefaults()

var blog = Blog()
blog.blogName = "My Blog"

ud.setObject(NSKeyedArchiver.archivedDataWithRootObject(blog), forKey: "blog")

if let data = ud.objectForKey("blog") as? NSData {
    let unarc = NSKeyedUnarchiver(forReadingWithData: data)
    let newBlog = unarc.decodeObjectForKey("root") as Blog
}

这篇关于使用 NSCoding 将自定义 Swift 类保存到 UserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆