我们可以更新存储在NSUserDefault中的数组

时间:2012-11-05 08:19:16

标签: iphone ios nsuserdefaults

我将值存储在数组中,并将该数组存储在NSUserDefault中,然后我需要更新该数组,我可以这样做。如果那么怎么样?

3 个答案:

答案 0 :(得分:4)

首先检索当前数据。

    NSArray *tempNew = [[NSArray alloc]init];
    tempNew = [storeData objectForKey:@"accounts"];
    [tempArr addObjectsFromArray:tempNew];

更新

    [tempArr addObject:str];
    [storeData setObject:tempArr forKey:@"accounts"];

答案 1 :(得分:1)

NSUserDefaultsNSDictionary一样,因此您可以使用相同的方法更新字典,方法是将另一个对象设置为键值-setObject:forKey:

例如,当您尝试下面的代码

NSUserDefaults *usr=[NSUserDefaults standardUserDefaults];
NSArray *arr= [NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:2], nil];
[usr setObject:arr forKey:@"num"];
NSLog(@"usr %@",[usr arrayForKey:@"num"]);

NSUserDefaults *usr1=[NSUserDefaults standardUserDefaults];
NSArray *arr= [NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber 
                          numberWithInt:3], nil];
[usr setObject:arr forKey:@"num"];
NSLog(@"user1 %@",[usr1 arrayForKey:@"num"]);

你会得到

usr(     1,     2 ) usr1(     2,     3 )

在控制台中。

答案 2 :(得分:0)

只需在用户默认值中重新存储数组,然后调用synchronize

例如:

存储您的阵列......

NSMutableArray *yourArray = .... // whatever you did to create your data

// store your data in the NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:yourArray forKey:@"myArray"];
[defaults synchronize];

...然后在您的应用中某处的其他时间更新它!

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

// retrieve your data from the NSUserDefaults
NSMutableArray *yourArray = [defaults objectForKey:@"myArray"];

// edit the data, for example add some object.
[yourArray addObject:someNewObject]; 

// update the defaults
[defaults setObject:yourArray forKey:@"myArray"];
[defaults synchronize];