转 NSOperation和NSURLConnection

最近一个客户向我汇报了一个程序的问题。经过分析发现问题是NSURLConnection没有正常工作。记得以前测试时没有问题啊。后来上网查到 原来在iOS 4.0以后,NSURLConnection无法在NSOperation中正常运行,换句话说,NSURLConnection只能运行于主线程。解决 方法其实倒是蛮简单(比如我的程序在download中):

1
2
3
4
5
6
7
8
9
10
11
12
- ( void )download
{
    // NSURLConnectionn won't work if it's not in the main thread
    if ( ! [ NSThread isMainThread ] )
    {
        [self performSelectorOnMainThr ead : @selector (download ) withObject : nil waitUntilDone : NO ];
        return;
    }
   
    NSURLRequest *request = [ NSURLRequest requestWithURL : [ NSURL URLWithString :_urlString ] ];
    _connection = [ [ NSURLConnection alloc ] initWithRequest :request delegate :self ];     
}

你可能感兴趣的:(职场,休闲,NSURLConnection,NSOperation)