Save NSMutableArray in NSUserDefaults

怎甘沉沦 提交于 2019-12-11 05:53:14

问题


I need to save a NSMutableArray to NSUserDefaults.

I have tried this, but the load method returns a nil NSMutableArray :

//    NSMutableArray *listaAenviar = [[NSMutableArray alloc]init];

 -(void) saveArray {
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
[_listaAenviar addObject:@"1"];
[currentDefaults setObject:[NSKeyedArchiver archivedDataWithRootObject:[_listaAenviar mutableCopy]] forKey:@"listaAenviar"];
[currentDefaults synchronize];
 } 

 -(void) loadArray {
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
_listaAenviar = [currentDefaults objectForKey:@"listaAenviar"];
 }

回答1:


Try using these methods to save an array, a lot easier.

-(void)saveData :(NSMutableArray *)dataArray
{
    NSFileManager *filemgr;
    NSString *docsDir;
    NSArray *dirPaths;

    filemgr = [NSFileManager defaultManager];

    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(
                                                   NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = [dirPaths objectAtIndex:0];

    // Build the path to the data file
   NSString *dataFilePath = [[NSString alloc] initWithString: [docsDir
                                                      stringByAppendingPathComponent: @"data.archive"]];

    [NSKeyedArchiver archiveRootObject:
     dataArray toFile:dataFilePath];
}


-(NSMutableArray *)loadData
{
    NSFileManager *filemgr;
    NSString *docsDir;
    NSArray *dirPaths;

    filemgr = [NSFileManager defaultManager];

    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains(
                                                   NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = [dirPaths objectAtIndex:0];

    // Build the path to the data file
    NSString *dataFilePath = [[NSString alloc] initWithString: [docsDir
                                                      stringByAppendingPathComponent: @"data.archive"]];

    // Check if the file already exists
    if ([filemgr fileExistsAtPath: dataFilePath])
    {
        NSMutableArray *dataArray;

        dataArray = [NSKeyedUnarchiver
                     unarchiveObjectWithFile: dataFilePath];

        return dataArray;
    }
    return NULL;
}


来源:https://stackoverflow.com/questions/13143039/save-nsmutablearray-in-nsuserdefaults

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