2012-06-02 44 views
0

我做了很多的请求到服务器:这是处理背景的正确方法吗?

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 ?? 

感谢

+0

Pelase后喜的功能“更新” –

+0

代码,谢谢你的回应。更新功能可以是任何东西。现在它只是一个空的函数。我把一个NSLog中,它永远不会被调用 – BlackMouse

+0

“处理结果数据”它处理用户界面或一些共享存储? –

回答

1

正如你在这一领域的更新UI

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线程中调用则是你必须做

2

我不认为NSURLConnectionDelegate有一个request:finished:方法?并通过查看您的代码,它接近您的使用MBRequest。如果是这样,我强烈认为你应该看看他们的网页,例如如何使用块来做到这一点。

相关问题