Unable to retrieve NSMutableArray from NSUserDefau

2019-09-06 15:53发布

问题:

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

回答1:

NSUserDefaults always return immutable instances.

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



回答2:

[[NSUserDefaults standardUserDefaults] synchronize]

To dump all the contents from NSUserDefaults onto persistent store



回答3:

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:

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.

}