Jessica Liu
Jessica Liu

Reputation: 1

Fail to addObject to NSMutableArray

I am building this 'Add to favorite' with NSUserDefault. I am having this issue when adding array to NSMutableArray. Does anyone knows what I did wrong? Thank you very much.

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *favoriteRecipes = [[NSMutableArray alloc] init];


if ([prefs objectForKey:@"myFavor"] == nil) {
    //create the array
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [prefs setObject:array forKey:@"myFavor"];
    [array release];
}
NSMutableArray *tempArray = [[prefs objectForKey:@"myFavor"] mutableCopy];
favoriteRecipes = tempArray;
[tempArray release];

NSArray *charArray = [[NSArray alloc] initWithObjects: @"test1", @"test2" , nil];

//add the recipe
[favoriteRecipes addObject:[charArray objectAtIndex:0]];  

//save the array to NSUserDefaults
[prefs setObject:favoriteRecipes forKey:@"myFavor"];
[prefs synchronize];

Upvotes: 0

Views: 896

Answers (2)

janusfidel
janusfidel

Reputation: 8106

done something like this yesterday. see my code below. im not sure if you want the same thing like I did.

NSDictionary *tempDictionary = [NSDictionary dictionaryWithObjectsAndKeys:productID,@"ID",productTitle,@"title",productPrice,@"price",imageUrl,@"image",shipping,@"shipping_day", nil];

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *cartList = [[defaults objectForKey:@"CART_ITEMS"] mutableCopy];

if(!cartList)
    cartList = [[NSMutableArray alloc] init];

if([cartList indexOfObject:tempDictionary] == NSNotFound)
{
    NSLog(@"add favorite");
    [cartList addObject:tempDictionary];
    [defaults setObject:cartList forKey:@"CART_ITEMS"];
    [defaults synchronize];
    [sender setTitle:@"Remove" forState:UIControlStateNormal];
}
else
{
    NSLog(@"remove favorite");
    [cartList removeObject:tempDictionary];
    [defaults setObject:cartList forKey:@"CART_ITEMS"];
    [defaults synchronize];
    [sender setTitle:@"Add to cart" forState:UIControlStateNormal]; 
}

this is what I do everytime I want my favorite list from NSUserDefault

-(void)getCartList
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *cartList = [[defaults objectForKey:@"CART_ITEMS"] mutableCopy];
productListArr = [NSMutableArray arrayWithArray:cartList];
NSLog(@"cart list data == %@", cartList);
}

Upvotes: 0

Narayana Rao Routhu
Narayana Rao Routhu

Reputation: 6323

favoriteRecipes = tempArray;

instated of above line use be below line it will work fine 

[favoriteRecipes addObjectsFromArray:tempArray];

Upvotes: 1

Related Questions