NSMutableArray添加元素在iPhone中被覆盖

时间:2014-01-30 15:28:10

标签: ios objective-c nsmutablearray

每当用户选择国家/地区时,我都会尝试向NSMutableArray添加元素。但每次我使用[myarray setobject:@""];时,它都会添加新值,覆盖旧值。我想要这个数组,因为我正在使用它:

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

我想要一个数组,即使在应用程序关闭后也会维护用户选择的国家/地区列表。

我该怎么办?

3 个答案:

答案 0 :(得分:2)

setObject替换数组中的所有对象

例如,

NSUserDefault获取价值:

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

你应该使用[myMutableArray addObject:"aCountry"];而不覆盖,但只添加

之后

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

修改

-(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];

 }

答案 1 :(得分:0)

你问两件不同的事情。首先,-setObject:不是NS(Mutable)Array方法。您可能正在寻找-addObject:方法。因此,要将对象添加到NSMutableArray,您需要执行以下操作:

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

您要实现的第二件事是将数组存储在NSUserDefaults中。为此,在将对象添加到所需的数组后,您应该这样做:

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

答案 2 :(得分:0)

// 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];