Search code examples
iphoneobjective-cnslog

why element over released in array in nslog statement


My app crashed when run to NSLog(@"...") statement, and the log on console showed an object was double freed. I used zombie instrument to check it, and got that one of strings in myAreas was over released. But I cannot understand why it happened? Any help? Thank you.

NSString *myArea = @"Europe";
NSArray *myTimeZones = [NSTimeZone knownTimeZoneNames];
NSMutableArray *myAreas = [NSMutableArray arrayWithCapacity:1];
[myTimeZones enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSString *name = (NSString *)obj;
    if ([name hasPrefix:myArea]) {
        NSString *tmpArea = [name substringFromIndex:myArea.length+1];
        [myAreas addObject:tmpArea];
    }
}];
NSLog(@"My Cities in %@ time zone: %@", myArea, myAreas);

Solution

  • NSMutableArray is not thread safe, thus it can lead to subtle bugs when used in different threads, drop NSEnumerationConcurrent and it should work fine.