2012-02-25 45 views
0

我有这段代码,但我不明白为什么我必须在主线程上运行此代码。 如果我在后台运行它不会执行发布请求。这是一个错误吗? 我该如何解决这个问题?NSURLConnection当我在后台运行它时出现错误....我该如何解决?

- (void)setRead:(MWFeedItem *)entry 
{ [self getToken:YES]; 

    NSString *url=[NSString stringWithFormat:@"https://www.google.com/reader/api/0/edit-tag?a=user/-/state/com.google/read&i=%@&T=%@", entry.identifier, token]; 

    [self postRequestWithURLState:url]; 

} 
- (void)postRequestWithURLState:(NSString *)url 
{ 
    NSString *bodyRequest = nil; 
    NSURL *requestURL = [NSURL URLWithString:url]; 
    NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init]; 

    //NSLog(@"-------------- bodyRequest: %@", bodyRequest); 



    [theRequest setURL:requestURL]; 
    [theRequest setTimeoutInterval:0.5]; 
    [theRequest setHTTPMethod:@"POST"]; 
    [theRequest setHTTPBody:[bodyRequest dataUsingEncoding:NSASCIIStringEncoding]]; 
    [self.oauthAuthentication authorizeRequest:theRequest]; 
    [NSURLConnection connectionWithRequest:theRequest delegate:self]; 

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 



} 

这是我的电话:

-(void)segnaLettura:(MWFeedItem *)item{ 

     [reader setRead:item]; 

} 
- (void) segnaread:(MWFeedItem *)item{ 
    [self performSelectorOnMainThread:@selector(segnaLettura:) withObject:item waitUntilDone:NO]; 
} 

回答

1

为了异步NSURLConnection的功能,它需要线程的runloop进行处理。当新线程自动获得runloop时,由您来运行。

你可以学习如何在Threading Programming Guide中做到这一点,我可以更多地解释它,但大多数时候这不是你想要的。大部分时间在iOS中,后台线程应该使用NSOperation或GCD进行管理。一般来说,如果你在iOS 4+上手动产生线程,你就错了。有例外,但并不常见。

这里的第一个问题应该是“为什么我甚至有这样的后台线程?”

如果你确实需要一个后台线程,那么你的做法segnaread可能是好的。

+0

我使用segnaread将我的项目标记为在Google阅读器中阅读。当连接速度很慢时,它会冻结我的GUI几秒钟!这就是为什么我需要在后台真正做到这一点。我认为我在主线程上运行的代码行冻结了我的应用程序 – 2012-02-26 00:37:45

+0

如果连接到网络会冻结您的应用程序,那么您的操作不正确。解决方案是不移动到后台线程,但找出您正在同步连接到网络的位置。仪器可以在这里有所帮助。在Time Profiler的主线程中使用“对所有线程状态进行采样”。如果你不确定,这会告诉你你挂在哪里。 – 2012-02-27 14:29:13

+0

非常感谢 – 2012-02-29 23:28:32

相关问题