I am reading and writing an array to NSuserdefults in this way:
indexDelete = button.tag;
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:@"save"];
if (dataRepresentingSavedArray != nil)
{
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil)
myIntegers = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
myIntegers = [[NSMutableArray alloc] init];
}
[myIntegers addObject:[NSNumber numberWithInteger:indexDelete]];
NSLog (@"Array myIntegers: %@", myIntegers);
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:myIntegers] forKey:@"save"];
Every thing works fine if I keep the line:
myIntegers = [[NSMutableArray alloc] init];
out of the brackets, because even if the data is there, it is not written or read correctly:
I get this error: -[NSKeyedUnarchiver initForReadingWithData:]: data is NULL
What im I doing wrong??
You never initialize your
myIntegers. The first time you get the object for keysavefrom your defaults you get anilobject (hence not entering theifclosure and allocating the structure). After that you try to archive anilobject, which is probably the cause for the error you’re getting.Try moving the initialization of the array before this and only adding the objects from the previous saving if they exist: