I have made a category for saving number of app runs like so,
static NSString * const AppRuns = @"IP_AppRuns";
@implementation NSUserDefaults (RegisteredUser)
+ (void)saveRuns:(NSNumber *)value
{
[[NSUserDefaults standardUserDefaults] setObject:value forKey:AppRuns];
}
+ (NSNumber *)runs
{
return [[NSUserDefaults standardUserDefaults] objectForKey:AppRuns];
}
....
And I'm setting it in my App delegate didFinishLaunchingWithOptions
method.
[NSUserDefaults saveRuns: @(21)];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"App has run %ld times", [[NSUserDefaults runs] integerValue]);
But, I get EXC_BAD_ACCESS, which makes me suspect that it isn't getting saved.
However, the following works:
[[NSUserDefaults standardUserDefaults] setObject:@(17) forKey:@"AppRuns"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"App has run %ld times", [[[NSUserDefaults standardUserDefaults] valueForKey:@"AppRuns"] integerValue]);
What am I doing wrong?
+ (NSNumber *)runs
uses objectForKey
to access NSUserDefaults
Your second example uses valueForKey
to access NSUserDefaults
valueForKey
and objectForKey
both will return the object for the given key. But here valuForKey
is key-value coding (KVC).
If key does not start with “@”, invokes objectForKey:
. If key does start with “@”, strips the “@” and invokes [super valueForKey:]
with the rest of the key.
EDITED
Can you reinstall your app(clean old NSUserDefaults
values) and try this code?
@implementation NSUserDefaults (RegisteredUser)
+ (void)saveRuns:
{
NSNumber *runs = [[NSUserDefaults standardUserDefaults] objectForKey:AppRuns];
[[NSUserDefaults standardUserDefaults] setObject:runs++ forKey:@"Runs"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
+ (NSNumber *)runs
{
return [[NSUserDefaults standardUserDefaults] objectForKey:@"Runs"];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.