Reputation: 1003
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"];
}
Upvotes: 1
Views: 1772
Reputation: 4440
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;
}
Upvotes: 2