user3162102
user3162102

Reputation: 105

NSMutableArray adding elements get overwritten in iPhone

I'm trying to add elements to an NSMutableArray whenever a user selects a country. But each time I use [myarray setobject:@""];, it's adding the new value, overwriting my old value. I want this array as I'm using it in:

[[NSUserDefaults standardUserDefaults]setObject:(NSMutableArray *)selectedCountriesByUser forKey:@"userSelection"];
[[NSUserDefaults standardUserDefaults]synchronize];

I want an array which maintains the list of countries selected by the user even after the application is closed.

What should I do?

Upvotes: 0

Views: 257

Answers (3)

Funny
Funny

Reputation: 566

// ARRAY DECLARATION AND ASSIGNMENT OF VALUES TO IT    

NSMutableArray * selectedCountriesByUserArray=[[NSMutableArray alloc] init];
[selectedCountriesByUserArray addObject:@"value1"];
[selectedCountriesByUserArray addObject:@"value2"];
[selectedCountriesByUserArray addObject:@"value3"];

// STORING AN ARRAY WITH THE KEY "userSelection" USING NSUSERDEFAULTS

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:selectedCountriesByUserArray forKey:@"userSelection"];
[defaults synchronize];

Upvotes: 0

Ilario
Ilario

Reputation: 6079

setObject replace all objects in array

for example, get value from NSUserDefault:

NSMutableArray *myMutableArray = [NSMutableArray arrayWithArray:[[NSUserDefault standardUserDefault] objectForKey:"userSelection"]];

you should use [myMutableArray addObject:"aCountry"]; without overwriting, but adding only

and after

[[NSUserDefaults standardUserDefaults]setObject:myMutableArray forKey:@"userSelection"];
[[NSUserDefaults standardUserDefaults]synchronize];

EDIT:

-(void) viewDidLoad {

   //your selectedCountriesByUser
   myMutableArray = [NSMutableArray arrayWithArray:[[NSUserDefault standardUserDefault] objectForKey:"userSelection"]];

 }

...

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {

     //add object to array
     [myMutableArray adObject:"yourObj"];

    [[NSUserDefaults standardUserDefaults]setObject:myMutableArray forKey:@"userSelection"];
    [[NSUserDefaults standardUserDefaults]synchronize];

 }

Upvotes: 2

Bruno Koga
Bruno Koga

Reputation: 3874

You're asking two different things. First, -setObject: is not a NS(Mutable)Array method. You are probably looking for the -addObject: method. So, to add an object to your NSMutableArray, you need to do:

[myMutableArray addObject:yourObject] 
//Remember that `-addObject` is present only in NSMutableArray, not in NSArray

The second thing you are trying to achieve is to store the array in NSUserDefaults. to do so, after you add the object to the array you want, you should be fine do to so:

[[NSUserDefaults standardUserDefaults] setObject:myMutableArray forKey:@"userSelection"];
[[NSUserDefaults standardUserDefaults] synchronize];

Upvotes: 0

Related Questions