在NSUserDefaults中保存NSMutableArray

时间:2012-10-30 16:02:41

标签: objective-c nsuserdefaults

我需要将NSMutableArray保存到NSUserDefaults

我试过这个,但是load方法会返回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 个答案:

答案 0 :(得分:2)

尝试使用这些方法来保存数组,更容易。

-(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;
}