Unable to retrieve NSMutableArray from NSUserDefau

2019-09-06 15:08发布

I have an issue persisting data in local storage for an NSMutableArray containing a list of NSStrings. I have a save method and a get method both appear to work when the app is running. However, once I close the app and restart the items in the array are gone.

NSMutableArray*ImageTags;

Get Data

-(NSMutableArray*)GetDataNSMutableArray:(NSString*)ItemName
{
    NSMutableArray *GetData = [[NSMutableArray alloc] init];
    NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
    NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:ItemName];
    if (dataRepresentingSavedArray != nil)
    {
        NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
        if (oldSavedArray != nil)
            GetData = [[NSMutableArray alloc] initWithArray:oldSavedArray];
        else
            GetData = [[NSMutableArray alloc] init];
    }
    return GetData;
}

Save Data

-(void)SaveDataNSMutableArray:(NSString*)ItemName:(NSMutableArray*)Data
{
    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:Data] forKey:ItemName];

}

How items are added

[ImageTags addObject:Control.titleLabel.text]

How array is saved

[super SaveDataNSMutableArray:CVC_ImageURL:ImageTags];

How array is retrieved

ImageTags = [super GetDataNSMutableArray:CVC_ImageURL];

4条回答
Bombasti
2楼-- · 2019-09-06 15:43

NSUserDefaults always return immutable instances.

Unrelated: (Conventions says that methodNames should always begin with a small letter).

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-09-06 15:46

Your can not store mutable array to user defaults. Store the immutable copy and retrieve that and convert to mutable ones to access during the next launch.

查看更多
放荡不羁爱自由
4楼-- · 2019-09-06 15:54
[[NSUserDefaults standardUserDefaults] synchronize]

To dump all the contents from NSUserDefaults onto persistent store

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-09-06 16:01

You can do synchronization while saving:

-(void)SaveDataNSMutableArray:(NSString*)ItemName:(NSMutableArray*)Data
{
    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:Data] forKey:ItemName];

[[NSUserDefaults standardUserDefaults] synchronize] //add this code of a line.

}
查看更多
登录 后发表回答