Grand Central Dispatch - 在线程之间传递数据
我试图在后台运行一个进程来生成一个字符串,然后在主线程中使用该字符串(发送到远程服务器)。该代码在模拟器中运行良好,并且该字符串按预期记录两次。
在设备(iPad、4.2 和各种 iPhone)上,每次都会因 EXC_BAD_ACCESS 崩溃。似乎 myString 超出了范围,但这似乎与维基百科上的示例背道而驰使用相同的原理。
代码如下:
dispatch_async(_queue, ^{
NSString *myString = [self generateString];
NSLog(@"1 String is %@", myString);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"2 String is %@", myString);
});
});
有谁知道为什么会崩溃,以及修复它的最佳方法?
我犯了简化代码以使问题清晰的错误。
在主队列上,我实际上向自己发送了另一个呼叫的消息,这会导致访问错误。
解决方案是在我的异步队列上调用该方法,并在该方法内将代码包装在dispatch_async(dispatch_get_main_queue(), ^{});中。堵塞。
希望这对其他人有帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我犯了简化代码以使问题清晰的错误。
在主队列上,我实际上向自己发送了另一个呼叫的消息,这会导致访问错误。
解决方案是在我的异步队列上调用该方法,并在该方法内将代码包装在dispatch_async(dispatch_get_main_queue(), ^{});中。堵塞。
希望这对其他人有帮助。
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.
我的猜测是 NSString 是一个自动释放对象,因此它会超出范围并在主队列代码块中使用之前被释放。尝试将保留/释放添加到 NSString:
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: