2012-10-30 85 views
1

我需要将NSMutableArray保存为NSUserDefaults在NSUserDefaults中保存NSMutableArray

我已经试过这一点,但负载方法返回一个nilNSMutableArray

// 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"]; 
} 

回答

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; 
} 
+0

thx很多!它工作 – Ladessa

+0

如果我添加一个自定义对象到NSMutableArray工作这个方法? – Ladessa

+0

是的,数组可以存储任何类型的对象,所以它存储什么对象并不重要 – AdamM

相关问题