Reputation: 1471
Good morning, I made an IBAction method which saves some objects to an array:
-(IBAction)saveToFav:(id)sender
{
NSUserDefaults *newDefaults = [NSUserDefaults standardUserDefaults];
favorites = [[NSMutableArray alloc]initWithArray:[newDefaults mutableArrayValueForKey:@"favorites"] copyItems:YES];
// check if array already contains an object
if (![favorites containsObject:self.title])
{
[favorites addObject:self.title];
}
[newDefaults setObject:favorites forKey:@"favorites"];
}
However, when I call this method app crashes with error:
[NSKeyValueSlowMutableArray getObjects:range:]: value for key favorites of object 0x8939030 is nil'
Why this happens ? Thanks!
Max
Upvotes: 0
Views: 863
Reputation: 949
When your app finishes loading add this:
NSMutableArray *array = [[NSMutableArray alloc]init];
[defaults setObject:array forKey:@"favorites"];
[defaults synchronize];
Upvotes: 1
Reputation: 949
It seems like your data (favorites) has not been written to your defaults.You can forcesave your defaults by running this:
[[NSUserDefaults standardUserDefaults] synchronize];
Upvotes: 2
Reputation: 6372
In this line
favorites = [[NSMutableArray alloc]initWithArray:[newDefaults mutableArrayValueForKey:@"favorites"] copyItems:YES];
nil
is being assigned to favorites
. The reason for this is that newDefaults
is only just built on the previous line and is empty.
Upvotes: 1