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

时间:2012-06-02 08:59:14

标签: 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上运行回调,上面的代码是否正确?

  3. 此外,服务器请求代码有时会在以下位置崩溃:

    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    

    我得到了这个警告:

    Class _NSZombie_NSRunLoop is implemented in both ?? and ?? 
    

    提前致谢

2 个答案:

答案 0 :(得分:2)

我不认为NSURLConnectionDelegaterequest:finished:方法吗?并且通过查看您的代码,它会成为您的使用MBRequest。如果是这样,我强烈认为您应该查看他们的网页,例如如何使用块来执行此操作。

答案 1 :(得分:1)

在此段中更新用户界面时

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

然后必须在UI线程中调用然后是的,你必须这样做