当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - NSUserDefaults returning nil

问题描述:

Im trying to save an object to NSUserdefaults and then extract the same object.

// let raw: AnyObject! = defaults.valueForKey("testKey")

// let data = raw as NSData

//

// self.Report = NSKeyedUnarchiver.unarchiveObjectWithData(data) as DayReport

//

// println(Report.Day)

Report.Day = "Mon"

let data = NSKeyedArchiver.archivedDataWithRootObject(self.Report)

println(data)

defaults.setObject(data, forKey: "testKey")

defaults.synchronize()

In this piece of code I save the object Report into NSUserDefaults encoded to NSData. DayReport is the type of Report

But when I switch the comment sections so the upper part of the code is not commented and the lower part is, the let var = (nil) and the program crashes. Why?

DayReport has the NSCoding protocol.

Update

I added this:

 defaults.setObject(data, forKey: "testKey")

defaults.synchronize()

println(defaults.objectForKey("testKey"))

And it prints out nil, so it isnt getting saved properly but the data is not nil.

网友答案:

You should not be using .valueForKey("testKey") because this is using KVC to try to get a key that doesn't exist.

Instead you should be using .objectForKey("testKey").

网友答案:

Here is the code for set value to NSuserDefaults...

 [[NSUserDefaults standardUserDefaults] setInteger:1  forKey:@"your key"];//Remember your key to get data from NSuserDefaults
[[NSUserDefaults standardUserDefaults] synchronize];

code for get value from NSuserDefaults...

  int CheckTimer = [[NSUserDefaults standardUserDefaults] integerForKey:@"your key"];

I hope this help you....

分享给朋友:
您可能感兴趣的文章:
随机阅读: