Iphone 在后台运行NSURLConnection时出现错误。。。。我该怎么修理?

Iphone 在后台运行NSURLConnection时出现错误。。。。我该怎么修理?,iphone,objective-c,ios,nsurlconnection,Iphone,Objective C,Ios,Nsurlconnection,我有这个代码,但我不明白为什么我必须在主线程上运行它。 如果我在后台运行,它不会执行post请求。是虫子吗? 我怎样才能解决这个问题 - (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/re

我有这个代码,但我不明白为什么我必须在主线程上运行它。 如果我在后台运行,它不会执行post请求。是虫子吗? 我怎样才能解决这个问题

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

为了使异步
NSURLConnection
正常工作,它需要处理线程的runloop。虽然新线程会自动获得一个runloop,但它的运行取决于您

你可以在课堂上学习如何做到这一点,我可以做更多的解释,但大多数时候这不是你想要的。在iOS中,大多数情况下,后台线程都应该使用
NSOperation
或GCD进行管理。通常,如果您在iOS 4+上手动生成线程,那么您就错了。也有例外,但并不经常

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


如果你真的需要一个后台线程,那么你所使用的
segnead
方法可能很好。

我使用segnead将我的项目标记为在GoogleReader中读取。当连接速度慢时,它会将我的GUI冻结几秒钟!这就是为什么我需要在后台做这件事。我认为我在主线程上运行的代码行冻结了我的应用如果连接到网络冻结了你的应用,那么你做得不对。解决方案不是移动到后台线程,而是找出同步连接到网络的位置。仪器在这方面很有用。仅在主线程时间分析器上使用“采样所有线程状态”。如果你不确定的话,这会告诉你挂在哪里。