【发布时间】:2016-11-04 12:28:51
【问题描述】:
我在自定义操作中收到了一个同步请求,如下所示:
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *_data, NSURLResponse *_response, NSError *_error)
{
self->data = [_data retain];
self->tempResponse = _response;
self->tempError = [_error retain];
self->done = true;
}];
[task resume];
// wait until the connection has finished downloading the data or the operation gets cancelled
while (!self->done && !self.isCancelled)
{
[[NSRunLoop currentRunLoop] run];
}
这段代码已经很老了,但已经在多个 iOS 版本中运行过(只是在某些时候替换了 NSURLConnection)。现在在 iPad Pro 上的 iOS 10 下,此代码将冻结我的应用程序。如果我将应用程序置于后台并重新打开它,它将再次运行。此外,如果我在 [task resume] 和 self->data = [_data retain]; 上设置断点,则根本不会发生冻结。
我找到了一种在代码中修复它的方法,即在运行循环中添加一个 NSLog:
while (!self->done && !self.isCancelled)
{
NSLog(@"BLAH!");
[[NSRunLoop currentRunLoop] run];
}
这会消耗相当多的性能,并且从长远来看无济于事,因为所有 NSLog 都已为发布配置删除。
所以我需要一种方法来修复这个错误。也许代码太旧了,有一种新的方法可以做到,我不知道。任何帮助表示赞赏。
【问题讨论】:
-
也许 runUntil 提前一小段时间运行,直到有帮助...
-
我已经尝试了 runUntil: 和 runMode:beforeDate:,但没有任何效果:(
-
一般来说,使用 dispatch_semaphore 或 dispatch group 可能会更好。
标签: objective-c ios10 nsrunloop