IntegerForKey always crashes the application

Retrieving a value from standardUserDefaults using integerForKey after saving with setInteger: forKey always crashes the application.

If I get the value using objectForKey and the cast value is for int, there are no errors, and I can show the value in the log message in order. However, when I try to assign this int to another int, or try to execute a mathematical function on it, such as adding, it also disconnects the application.

How to get the int that I saved in standardUserDefaults? I am developing against SDK 3.0, but am experiencing an identical issue in 2.2.1. Thanks.

prefix defined as

NSUserDefaults *prefs;

and retrievePrefs is always called before savePrefs. The application also calls [prefs synchronize] before exiting.

-(void)retrievePrefs {
    prefs = [[NSUserDefaults standardUserDefaults] retain];
    if (prefs) {
       // doesn't crash app, spits out 'page: 1'
       NSLog(@"page: %@", [prefs objectForKey:@"pageIndex"]); 

       // crashes app with no details
       NSLog(@"page: %@", [prefs integerForKey:@"pageIndex"]); 
    }
}


-(void)savePrefs {
    if (prefs) {
        [prefs setInteger:1 forKey:@"pageIndex"];
    }
}
+3
source share
1 answer

Your second call to NSLog calls it: the qualifier is %@used to print Objective-C or CoreFoundation CFTypeRefs objects, so it interprets this integer as a pointer and tries to dereference it.

What you need:

-(void)retrievePrefs {
    prefs = [[NSUserDefaults standardUserDefaults] retain];
    if (prefs) {
        NSLog(@"page: %@", [prefs objectForKey:@"pageIndex"]);
        NSLog(@"page: %ld", (long)[prefs integerForKey:@"pageIndex"]);
    }
}

For more information, refer to the API documentation for NSLog, printfand -[NSString stringWithFormat:].

+4
source

Source: https://habr.com/ru/post/1708133/


All Articles