I'm trying to run a process in the background to generate a string, which is then used in the main thread (sent to a remote server.) The code works fine in the simulator, and the string is logged twice as expected.
On a device (iPad, 4.2 and various iPhones) it crashes every time with EXC_BAD_ACCESS. It seems that myString goes out of scope, but this seems to go against the example on Wikipedia where the same principle is used.
The code is as follows:
dispatch_async(_queue, ^{
NSString *myString = [self generateString];
NSLog(@"1 String is %@", myString);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"2 String is %@", myString);
});
});
Does anyone know why this crashes, and the best way to fix it?
I made the mistake of simplifying my code to keep my question clear.
On the main queue I actually message self with another call and this causes the bad access.
The solution was to call the method on my async queue, and inside the method wrap the code in the dispatch_async(dispatch_get_main_queue(), ^{}); block.
Hopefully this will help someone else.
self
. – bbum