insert object in an NSMutableArray saved with NSUserDefaults

只谈情不闲聊 提交于 2019-11-27 15:28:15
lxt

NSUserDefaults always returns immutable objects, even if the original object was mutable. It's in the documentation for objectForKey:

The returned object is immutable, even if the value you originally set was mutable.

You will need to create a copy of the returned object before you modify it, using [NSMutableArray arrayWithArray:]

Probably also best to use the arrayForKey method of NSUserDefaults if you're retrieving an array. Docs here: https://developer.apple.com/documentation/foundation/userdefaults

Here is a complete working example:

- (void)saveScore:(NSNumber *)score
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *scoreList = [[NSMutableArray alloc] initWithArray: [defaults objectForKey:@"ScoreList"]];
    [scoreList addObject:score];
    [defaults setObject:scoreList forKey:@"ScoreList"];
    [defaults synchronize];
}

First we read in the stored data in a mutable array, update the array, save the new array, and then synchronize the user defaults to permanently record the changes.

Hope this helps!

Another option is:

[[NSUserDefaults standardUserDefaults] setObject:[[[NSUserDefaults standardUserDefaults] objectForKey:@"12345"] arrayByAddingObject:object] forKey:@"12345"];
Amitabha

Copy Array from an NSUserDefault like this way :

[YourArray addObjectsFromArray:[[NSUserDefaults standardUserDefaults] 
                  objectForKey:@"NSUSD"]];

or

YourArray = [[NSMutableArray alloc] 
             initWithArray:[[NSUserDefaults standardUserDefaults]  
              objectForKey:@"NSUSD"]];
[YourArray addObject: (currentObject)];

It is because you NSMutablepointer points an NSUserDefault object directly. You should first copy NSUserDefault object to an array than process it.

NSMutableArray *arr= [NSMutableArray arrayWithObjects:@"asd",@"dsa",nil];
    [[NSUserDefaults standardUserDefaults] setObject:arr forKey:@"12345"];
NSMutableArray *abc = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"12345"]];
//[[NSUserDefaults standardUserDefaults] objectForKey:@"12345"];
    int n = [abc count];
    [abc insertObject:@"aaa" atIndex:n];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [[NSUserDefaults standardUserDefaults] setObject:abc forKey:@"12345"];
    [defaults synchronize];
    [abc release];

Quick fix:

_retrivedArray = [_mutableArray mutableCopy];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!