0

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.

Kgrover
  • 2,106
  • 2
  • 36
  • 54

2 Answers2

1

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:

The Kraken
  • 3,158
  • 5
  • 30
  • 67
0

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

Community
  • 1
  • 1
cloosen
  • 993
  • 7
  • 17