将自定义对象保存到NSUserDefaults [duplicate]

时间:2021-08-01 17:00:54

This question already has an answer here:

这个问题已经有了答案:

I'm having a news ViewController and a TeamViewController. The TeamViewController contain a tableView of teamObjects which when selected is added into array. I want to add this array into NSUserDefaults so i can access them from the NewsController which contain a url request where the teamObjects is needed. However i keep getting:

我有一个新闻视图控制器和一个TeamViewController。TeamViewController包含一个teamObjects的tableView,当被选中时,它被添加到数组中。我想将这个数组添加到NSUserDefaults中,这样我就可以从包含需要teamobject的url请求的NewsController中访问它们。然而我继续:

'Attempt to insert non-property list object ( "" ) for key teams'

'尝试为关键团队插入非属性列表对象(")'

I'm open for other suggestions if there is better ways than storing it in NSUserDefaults

如果有比将它存储在NSUserDefaults中更好的方法,我欢迎其他的建议

didSelectRowAtIndexPath method

didSelectRowAtIndexPath方法

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)


    let team = self.teamArray[indexPath.row] as Team
    var removed = false

    for (index, value) in enumerate(self.teamSelected) {
        if (value == team) {
            self.teamSelected.removeAtIndex(index)
            removed = true
        }
    }

    if (!removed) {
        self.teamSelected.append(team)
    }

    var userDefaults = NSUserDefaults.standardUserDefaults()
    userDefaults.setValue(self.teamSelected, forKey: "teams")
    userDefaults.synchronize()

    tableView.reloadData()
}

My object

我的对象

class Team: NSObject{
    var id: Int!
    var name: NSString!
    var shortname: NSString!


    init(id: Int, name:NSString, shortname: NSString) {
        self.id = id
        self.name = name
        self.shortname = shortname

    }

}

2 个解决方案

#1


145  

Actually, you will need to archive the custom object into NSData then save it to user defaults and retrieve it from user defaults and unarchive it again. You can archive it like this

实际上,您需要将自定义对象存档到NSData中,然后将其保存到用户默认值,并从用户默认值中检索它,并将其重新归档。你可以这样归档它

let teams = [Team(id: 1, name: "team1", shortname: "t1"), Team(id: 2, name: "team2", shortname: "t2")]

var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: teams)
userDefaults.set(encodedData, forKey: "teams")
userDefaults.synchronize()

and unarchive it like this

像这样解压

let decoded  = userDefaults.object(forKey: "teams") as! Data
let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Team]

But if you just did that you will get

但如果你这么做了,你会得到

.Team encodeWithCoder:]: unrecognized selector sent to instance

You will have to make Team conform to NSCoding just like this

你必须让团队像这样遵守NSCoding规则

class Team: NSObject, NSCoding {
    var id: Int
    var name: String
    var shortname: String


    init(id: Int, name: String, shortname: String) {
        self.id = id
        self.name = name
        self.shortname = shortname

    }

    required convenience init(coder aDecoder: NSCoder) {
        let id = aDecoder.decodeInteger(forKey: "id")
        let name = aDecoder.decodeObject(forKey: "name") as! String
        let shortname = aDecoder.decodeObject(forKey: "shortname") as! String
        self.init(id: id, name: name, shortname: shortname)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(id, forKey: "id")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(shortname, forKey: "shortname")
    }
}

#2


0  

You can try NSKeyedUnarchiver, like below

您可以尝试NSKeyedUnarchiver,如下所示

Here i stored UIColor Object in UserDefault You can change it with your object

这里我将UIColor对象存储在UserDefault中,您可以使用对象来更改它

 NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color];
[[NSUserDefaults standardUserDefaults] setObject:colorData forKey:@"myColor"];

and to retrive that

并索取

NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"];
UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];

Note : This is Objective C but I hope you can covert this in Swift

注意:这是Objective - C,但我希望你能在Swift中隐藏它

Hope this solve your problem

希望这能解决你的问题

#1


145  

Actually, you will need to archive the custom object into NSData then save it to user defaults and retrieve it from user defaults and unarchive it again. You can archive it like this

实际上,您需要将自定义对象存档到NSData中,然后将其保存到用户默认值,并从用户默认值中检索它,并将其重新归档。你可以这样归档它

let teams = [Team(id: 1, name: "team1", shortname: "t1"), Team(id: 2, name: "team2", shortname: "t2")]

var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: teams)
userDefaults.set(encodedData, forKey: "teams")
userDefaults.synchronize()

and unarchive it like this

像这样解压

let decoded  = userDefaults.object(forKey: "teams") as! Data
let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Team]

But if you just did that you will get

但如果你这么做了,你会得到

.Team encodeWithCoder:]: unrecognized selector sent to instance

You will have to make Team conform to NSCoding just like this

你必须让团队像这样遵守NSCoding规则

class Team: NSObject, NSCoding {
    var id: Int
    var name: String
    var shortname: String


    init(id: Int, name: String, shortname: String) {
        self.id = id
        self.name = name
        self.shortname = shortname

    }

    required convenience init(coder aDecoder: NSCoder) {
        let id = aDecoder.decodeInteger(forKey: "id")
        let name = aDecoder.decodeObject(forKey: "name") as! String
        let shortname = aDecoder.decodeObject(forKey: "shortname") as! String
        self.init(id: id, name: name, shortname: shortname)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(id, forKey: "id")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(shortname, forKey: "shortname")
    }
}

#2


0  

You can try NSKeyedUnarchiver, like below

您可以尝试NSKeyedUnarchiver,如下所示

Here i stored UIColor Object in UserDefault You can change it with your object

这里我将UIColor对象存储在UserDefault中,您可以使用对象来更改它

 NSData *colorData = [NSKeyedArchiver archivedDataWithRootObject:color];
[[NSUserDefaults standardUserDefaults] setObject:colorData forKey:@"myColor"];

and to retrive that

并索取

NSData *colorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"myColor"];
UIColor *color = [NSKeyedUnarchiver unarchiveObjectWithData:colorData];

Note : This is Objective C but I hope you can covert this in Swift

注意:这是Objective - C,但我希望你能在Swift中隐藏它

Hope this solve your problem

希望这能解决你的问题