Strange __block memory change error

I have a problem in my code that I overdid until the following (stupid) example

NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", nil]; __block NSString *a = @"-1"; [array enumerateObjectsUsingBlock:^(id whoCares, NSUInteger idx, BOOL *stop) { a = [NSString stringWithFormat:@"%@ %d", a, idx]; NSLog(@"%@", a); }]; NSLog(@"%@", a); 

This code works, but if I comment on the first NSLog (inside the block), the code will work. But if I changed the format string to the next

 a = [NSString stringWithFormat:@"%d", idx]; 

then the code works fine without NSLog inside the block.

What's going on here? I hope I'm just misunderstanding something.

+4
source share
1 answer

stringWithFormat: provides you with an auto-implemented object that you are not saving. By the time the block exits and you call NSLog , a may already be freed.

One solution might be to use a mutable string and append to it every time, rather than reassigning.

 NSArray *array = [NSArray arrayWithObjects:@"1", @"2", @"3", nil]; NSMutableString *a = [NSMutableString stringWithFormat:@"-1"]; [array enumerateObjectsUsingBlock:^(id whoCares, NSUInteger idx, BOOL *stop) { [a appendFormat:@" %d", idx]; }]; NSLog(@"%@", a); 
+2
source

All Articles