开发者

Crash while fetching NSUserDefaults

The following code is crashing 开发者_如何转开发for me

 [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"2453"];

I checked and found that there is no key with name 2453 in NSUserDefaults. I am running the application for first time so this key will not be there but will be added later point in time. How to ignore this crash.


If this line

[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"2453"];

is the line that is crashing, you might try this instead

NSDictionary *dict = nil;
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"2453"] != nil)
    dict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"2453"];

if (dict) {
    ...
}

My hunch is that in this case dictionaryForKey is calling objectForKey behind the scenes and blindly trying to cast nil to NSDictionary for you, which would, I think, cause a crash. But by checking yourself first if there is any kind of object for that key, you can avoid the crash. Give it whirl and report back! :-)


 [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"2453"];
 //                                                      ^^    ^

The "key" in -dictionaryForKey: must be an NSString. It cannot be an int. So although the key you supplied consists only of numbers, you still have to pass in a string using @"...". The fact that the key is absent is irrelevant to the crash.


if ([[NSUserDefaults standardUserDefaults] dictionaryForKey:@"2453"]) {
    // this line will only be reached if there is something for @"2453"
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜