8vius
8vius

Reputation: 5836

Program crashing when adding object to NSArray

I have the following IBAction set up:

#define FAVORITES_KEY @"GraphViewController.Favorites"
- (IBAction)addToFavorites:(id)sender {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *favorites = [defaults objectForKey:FAVORITES_KEY];
    if (!favorites) favorites = [NSMutableArray array];
    [favorites addObject:self.program];
    [defaults setObject:favorites forKey:FAVORITES_KEY];
    [defaults synchronize];
}

The first time this action is called it all works well, the object is added to my array and saved to NSUserDefaults without a problem, after that first call it will throw an exception when adding to the favorites array, if I try to step over the break it will say this:

Single stepping until exit from function objc_exception_throw, 
which has no line number information.

Catchpoint 3 (exception thrown).

Anyone had a similar issue or might know what's happening?

Upvotes: 0

Views: 113

Answers (1)

Costique
Costique

Reputation: 23722

NSUserDefaults returns an immutable array, so you need to convert it:

NSMutableArray *favorites = [[defaults objectForKey:FAVORITES_KEY] mutableCopy];
if (!favorites) favorites = [NSMutableArray new];
...
[favorites release];

Upvotes: 4

Related Questions