1

我需要保存一个NSMutableArrayNSUserDefaults.

我已经尝试过了,但是 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"];
 }
4

1 回答 1

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;
}
于 2012-10-30T16:08:06.753 回答