我向服务器做了很多请求:
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[theRequest setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
urlData = [[NSMutableData data] retain];
urlConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
if (urlConnection)
{
finishedLoading = FALSE;
while(!finishedLoading) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
else
{
[delegate swHttpConnection:self withRequest:urlString failedWithError:nil];
}
...请求完成后,我会收到回调。但是,如果我使用下面的代码,选择器将不会被调用:
- (void)request:(MBRequest *)request finished:(NSMutableArray *)resultArray
{
//Handle resultArray data
[self performSelector:@selector(someRandomFunction) withObject: nil afterDelay:1.0f];
}
..但是如果我使用下面的代码;它工作正常:
- (void)request:(MBRequest *)request finished:(NSMutableArray *)resultArray
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0), ^(void)
{
dispatch_async(dispatch_get_main_queue(), ^(void)
{
//Handle resultArray data
[self performSelector:@selector(someRandomFunction) withObject: nil afterDelay:1.0f];
});
});
}
所以我的问题是双重的。
这样做正确吗?我是否需要强制在 mainthred 上运行回调,或者代码的逻辑是否错误?
如果我必须强制在 mainthred 上运行回调,上面的代码是否正确?
此外,服务器请求代码有时会在以下位置崩溃:
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
我得到了这个警告:
Class _NSZombie_NSRunLoop is implemented in both ?? and ??
提前致谢
最佳答案
我不认为 NSURLConnectionDelegate
有一个 request:finished:
方法?并通过查看您的代码,它与您的使用 MBRequest 接缝.如果是这样,我强烈认为您应该查看他们的网页,例如如何使用 block 来执行此操作。
关于iphone - 这是处理后台线程的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10861048/