1
int ramdomnumber = arc4random_uniform(900000) + 100000;
[[NSUserDefaults standardUserDefaults] setObject:ramdomnumber forKey:@"contactno"];
[[NSUserDefaults standardUserDefaults] synchronize];

i tried the above code but it showing the error like implicit conversion of 'int' to 'id_nullable' is disallowed with ARC.can anyone suggest me how to store the int value in the nsuserdefaults .

pavithra
  • 47
  • 1
  • 10
  • int ramdomnumber = arc4random_uniform(900000) + 100000; [[NSUserDefaults standardUserDefaults] setObject:@(ramdomnumber) forKey:@"contactno"]; [[NSUserDefaults standardUserDefaults] synchronize]; – Sargis Apr 18 '17 at 10:45

3 Answers3

4

The error occurs because you are passing a scalar type to a method which expects an object.

There is a dedicated method, it's good programming habit to cast the value to the expected type;

NSInteger ramdomnumber = (NSInteger)(arc4random_uniform(900000) + 100000);
[[NSUserDefaults standardUserDefaults] setInteger:ramdomnumber forKey:@"contactno"];
// [[NSUserDefaults standardUserDefaults] synchronize];

synchronize is not needed.

vadian
  • 274,689
  • 30
  • 353
  • 361
2

The problem here is that int is not an Object, what you should do is:

int ramdomnumber = arc4random_uniform(900000) + 100000;
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:ramdomnumber] forKey:@"contactno"];
[[NSUserDefaults standardUserDefaults] synchronize];
Ricardo Alves
  • 642
  • 2
  • 13
  • 34
2

u can use NSNumber to store the integer values for example,

int ramdomnumber = arc4random_uniform(900000) + 100000;
 NSNumber *randomNo = [NSNumber numberWithInt: ramdomnumber]; 
[[NSUserDefaults standardUserDefaults] setObject: randomNo forKey:@"contactno"]; //save NSNumber instance not the int 
[[NSUserDefaults standardUserDefaults] synchronize];

to get integer back, same way,

NSNumber *savedNo = [[NSUserDefaults standardUserDefaults] objectForKey:@"contactno"];
int ramdomnumber = savedNo.intValue;//[savedNo intValue];
Shankar BS
  • 8,394
  • 6
  • 41
  • 53