There are some similar questions that already exist on StackOverflow. I did check them out, and in most cases it returns nil because the NSMutableArray has not been initialised. But in my case I did initialise it.
Here's part of my code :
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
self.storedTimeZones = [[NSMutableArray alloc] init];
NSData *storedData = [[NSUserDefaults standardUserDefaults] dataForKey:@"timeZones"];
if (storedData != nil ) {
self.storedTimeZones = [NSKeyedUnarchiver unarchiveObjectWithData:storedData];
}
NSString *str = [self.smallRegionArray[indexPath.row] stringByReplacingOccurrencesOfString:@"_" withString:@" "];
[self.storedTimeZones addObject: str];
NSLog(str); //the string was printed successfully.
NSLog(@"%lu", (unsigned long)self.storedTimeZones.count); //'0' was printed
}
update
@Caleb was right, [NSKeyedUnarchiver unarchiveObjectWithData:storedData returned nil. I solved it by doing this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
self.storedTimeZones = [[NSMutableArray alloc] init];
NSData *storedData = [[NSUserDefaults standardUserDefaults] dataForKey:@"timeZones"];
NSMutableArray *ary = [NSKeyedUnarchiver unarchiveObjectWithData:storedData];
if (ary != nil ) {
self.storedTimeZones = ary;
}
NSString *str = [self.smallRegionArray[indexPath.row] stringByReplacingOccurrencesOfString:@"_" withString:@" "];
[self.storedTimeZones addObject: str];
NSLog(str);
NSLog(@"%lu", (unsigned long)self.storedTimeZones.count); //Now it prints `1`
}
unarchiveObjectWithDatawill give you an immutable array. If you expectself.storedTimeZonesto be mutable, you should make a mutable copy:[[NSKeyedUnarchiver unarchiveObjectWithData:storedData] mutableCopy]- CalebmutableCopyas you suggested but still got theunrecognized selector sent to instanceerror when I run it. (just like what @trojanfoe predicted) - hklelself.storedTimeZonespoints to. I provided debugger commands in my answer. When you know what type of object you're dealing with, you'll understand why you're getting the exception and you should be able to figure out how you get that object instead of the mutable array that you expected. - Caleb