I am trying to make a favorite function, so you can add and remove favorites. I have a tableview and in the detail view (when you click at a row in the tableview) there is a button to add and remove things to favorite. In the simulator all works perfectly, but on my device it does not work.
This is my action when you click at the button. At first, this codes check if the array contains the object recipeName. recipeName is a string.
-(IBAction)favorites:(id)sender {
prefs = [NSUserDefaults standardUserDefaults];
if (![favoriteRecipes containsObject:recipeName]) {
Favoriten.image = [UIImage imageNamed:@"Favoriten_ausgefüllt_25x25.png"];
//add the recipe
[favoriteRecipes addObject:recipeName];
NSLog(@"Objects: %@", favoriteRecipes);
//save the array to NSUserDefaults
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:favoriteRecipes forKey:@"Favorites"];
[userDefaults synchronize];
} else {
Favoriten.image = [UIImage imageNamed:@"star-25.png"];
//add the recipe
[favoriteRecipes removeObject:recipeName];
NSLog(@"Objects: %@", favoriteRecipes);
//save the array to NSUserDefaults
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:favoriteRecipes forKey:@"Favorites"];
[userDefaults synchronize];
}
This code also saves the NSMutableArray with NSUserDefault. So in my favoriteController I am retrieving the data:
favoritesrecipes = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"Favorites"] mutableCopy];
FavoritenArray = [favoritesrecipes copy];
That's all. In the simulator all works perfectly but on my device not.