문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

My guess would be that the NSString is a autorelease object so it will go out of scope and released before it's used in the main queue code block. Try adding retain/release to the NSString:

dispatch_async(_queue, ^{

 NSString *myString = [self generateString];
 [myString retain];
 NSLog(@"1 String is %@", myString);
 dispatch_async(dispatch_get_main_queue(), ^{
  NSLog(@"2 String is %@", myString);
  [myString release];
 });

});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top