iphone - 这是处理后台线程的正确方法吗?

标签 iphone objective-c ios xcode nsoperationqueue

我向服务器做了很多请求:

    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]; 
        }); 
    }); 
}

所以我的问题是双重的。

  1. 这样做正确吗?我是否需要强制在 mainthred 上运行回调,或者代码的逻辑是否错误?

  2. 如果我必须强制在 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/

相关文章:

iphone - iPhone 不支持 ExposureMode AVCaptureExposureModeAutoExpose

iphone - KVC : How do I save UIKit structs in plist?

iphone - 根据最长宽度的 UITableViewCell 调整 UITableView 的宽度

iphone - UITextView 作为自己的委托(delegate)意味着无限循环

ios - LaunchScreen 未显示在任何设备和项目上

ios - ScrollView 内的UIButton不触发 Action

ios - MPMovieplayerViewController 有没有办法检测视频是否是流?

iphone - 从一个 View 导航到另一个 View 时制作翻转动画

objective-c - cocoa touch 。为什么 NSNumber 返回 intValue 和 floatValue 的差值?

ios - Objective-C @available 守卫与更多条件