Kgrover
Kgrover

Reputation: 2116

Bad Access on storing NSUserDefaults

I'm using the following code to save a number in NSUserDefaults:

NSUserDefaults *prefs = [[NSUserDefaults standardUserDefaults]retain];
NSNumber *num = [[NSNumber alloc]initWithInt:indexPath.row];
[prefs setValue:num forKey:@"randomkeyhere"];

Only at some points I get a

EXC_BAD_ACESS (code=2).

Am I doing anything wrong? Is this undefined behavior or something of that sort? I'm wondering why I only get it sometimes and not always.

Upvotes: 0

Views: 394

Answers (2)

The Kraken
The Kraken

Reputation: 3158

NSUserDefaults standardUserDefaults is a singleton object managed by iOS. It is not a new object that you initiate. Get rid of the retain.

Also, try setting a breakpoint in the method to see exactly where the program is crashing. Post the error's from the console below:

Upvotes: 1

cloosen
cloosen

Reputation: 993

in the singleton , the retain is like this

- (id)retain
{
    return self;
}

so , the retainCount will not add 1.

you can look at this :

singleton in objective c

Upvotes: 0

Related Questions