[英]NSUserDefaults returning nil
Im trying to save an object to NSUserdefaults
and then extract the same object. 我试图将对象保存到
NSUserdefaults
,然后提取相同的对象。
// 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
. 在这段代码中,我将对象Report保存到编码为
NSData
NSUserDefaults
中。 DayReport
is the type of Report
DayReport
是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. 但是,当我切换注释部分时,代码的上部不被注释,而下部是注释,
let var = (nil)
导致程序崩溃。 Why? 为什么?
DayReport
has the NSCoding
protocol. DayReport
具有NSCoding
协议。
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. 并且它打印出nil,因此无法正确保存它,但是数据不是nil。
You should not be using .valueForKey("testKey")
because this is using KVC to try to get a key that doesn't exist. 您不应该使用
.valueForKey("testKey")
因为这是使用KVC尝试获取不存在的密钥。
Instead you should be using .objectForKey("testKey")
. 相反,您应该使用
.objectForKey("testKey")
。
Here is the code for set value to NSuserDefaults... 这是将值设置为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... 从NSuserDefaults获取值的代码...
int CheckTimer = [[NSUserDefaults standardUserDefaults] integerForKey:@"your key"];
I hope this help you.... 希望对您有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.