- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSUserDefaults *somet = [NSUserDefaults standardUserDefaults];
NSMutableArray *anArr = [somet objectForKey:@"somedata"] ;
NSLog(@"anArr::: %@",anArr);
}
-(IBAction)addsomething:(id)sender{
if (something == nil) {
array = [[NSMutableArray alloc] init];
}
NSLog(@"textfieldvalue::: %@", textfield.text);
[array addObject:textfield.text];
NSUserDefaults *something = [NSUserDefaults standardUserDefaults];
[something setObject:array forKey:@"somedata"];
array = [something objectForKey:@"somedata"];
NSLog(@"array:: %@", array);
}
Using the above code, I am trying to save data dynamically in NSMutableArray and then saving it in NSUserDefaults. But on retrieving it I am getting (null). Even data is not being saved in array.
How to save data properly?
EDITED:
2012-03-15 15:17:18.431 check[2686:40b] anArr::: (null)
2012-03-15 15:17:30.160 check[2686:40b] textfieldvalue::: a
2012-03-15 15:17:30.162 check[2686:40b] array::: (null)
no offense, but your code is a big pile of crap.
something
are not useful. Period. I fixed it for you:
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSArray *anArr = [userDefaults objectForKey:@"somedata"];
NSLog(@"anArr::: %@",anArr);
}
-(IBAction)addsomething:(id)sender{
NSMutableArray *array = [[NSMutableArray alloc] init];
NSLog(@"textfieldvalue::: %@", textfield.text);
[array addObject:textfield.text];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:array forKey:@"somedata"];
array = [userDefaults objectForKey:@"somedata"];
// synchronize is only needed while debugging (when you use the stop button in Xcode)
// you don't need this in production code. remove it for release
[userDefaults synchronize];
NSLog(@"array:: %@", array);
}
However, most likely you want to save objects to the array you got from userDefaults. That won't work with local variables!
You would use something like this. But don't copy that verbatim. Try to understand it, and read more about local variables.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
array = [[userDefaults objectForKey:@"somedata"] mutableCopy];
if (!array) {
// create array if it doesn't exist in NSUserDefaults
array = [[NSMutableArray alloc] init];
}
NSLog(@"array in viewDidLoad: %@",array);
NSLog(@"textfieldvalue::: %@", textField.text);
[array addObject: textField.text];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:array forKey:@"somedata"];
// synchronize is only needed while debugging (when you use the stop button in Xcode)
// you don't need this in production code. remove it for release
[userDefaults synchronize];