Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integerForKey always crashes app

Tags:

objective-c

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

If I retrieve value using objectForKey and cast value to int, there are no errors and I can display value in a log message fine. However, when I attempt to assign that int to another int or try to perform a math function on it, like adding, it crashes app as well.

How do I retrieve an int that I've saved to standardUserDefaults? I'm developing against SDK 3.0 but have experienced identical issue in 2.2.1. Thanks.

prefs defined as

NSUserDefaults *prefs;

and retrievePrefs always called before savePrefs. App 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"];
    }
}
like image 820
sam Avatar asked Jan 26 '26 22:01

sam


1 Answers

Your second NSLog call is what's causing it: the %@ qualifier is used to print out Objective-C objects or CoreFoundation CFTypeRefs, so it's interpreting that integer as a pointer and attempting to dereference it.

What you need is:

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

Check the API documentation for NSLog, printf, and -[NSString stringWithFormat:] for more information.

like image 88
Jim Dovey Avatar answered Jan 28 '26 12:01

Jim Dovey