从iOS中的其他线程访问UI组件

问题描述:

我有关于如何刷新iOS应用程序的UI的问题。我想实现的是:基于从网络服务中检索数据 从iOS中的其他线程访问UI组件

  • Web服务应该从一个单独的线程调用(不是主线程)
  • 的数据是经过UITableView的

    1. 显示数据检索,将刷新的UITableView的内容与所检索数据
    2. 从而UI不会挂起或在不良网络连接
    3. 从web服务接收数据的过程中,应用程序不会阻止用户输入而这是由于

    要做到这一点,我创建了下面的源代码:

    - (void)viewDidLoad 
    { 
        [super viewDidLoad]; 
        NSURL *myURL = [[NSURL alloc] initWithString:[Constant webserviceURL]]; 
        NSURLRequest *request = [NSURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData      timeoutInterval:60]; 
        [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    } 
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ 
        NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; 
        [self myparser] = [[MyXMLParser alloc] initXMLParser]; 
    
        [parser setDelegate:myparser]; 
        BOOL success = [parser parse]; 
        if (success) { 
         // show XML data to UITableView 
         [_tableView performSelectorOnMainThread:@selector(reloadData) withObject:[myparser xmldata] waitUntilDone:NO]; 
        } 
        else { 
         NSLog(@"Error parsing XML from web service"); 
        } 
    } 
    

    ================== 是我的执行是否正确?任何人都知道如何解决它?

  • 你想打电话给

    + (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler 
    

    这将使调用来获取数据在不同的线程,则当数据拉下来,或者有问题从URL下载数据,它会调用处理块与原来的电话进行了同一线程

    下面是使用它的一种方法:https://*.com/a/9409737/1540822

    您还可以使用

    - (id)initWithRequest:(NSURLRequest *)request delegate:(id <NSURLConnectionDelegate>)delegate 
    

    ,这将调用您的NSURLConnectionDelegate方法之一,当数据卡盘下载。如果你要有大量数据,那么你可能会想要使用它,这样你就不会在响应中花费太多时间。

    +0

    嗨,谢谢你的回应。但是你知道另一个线程(不是主线程)如何访问UITableView对象并刷新UI本身吗? – ekychandra 2012-07-23 07:22:56

    +0

    tableview有一组需要更新的索引,它需要解析用户可能在屏幕上查看的索引,它必须等待单元离开屏幕或更新屏幕上这些单元的索引。你会想调用[self performSelector:@selector(doReloadTableData)withObject:NULL afterDelay:0.0]; – Pareshkumar 2012-07-23 11:45:14

    +0

    或者您可以使用 - performSelector:onThread:withObject:waitUntilDone:并将onThread:parm的MainThread交给它。第一个选项需要在另一个调用中打包,或者在获取数据时仅对main执行一个performSelection。 -------像你现在这样做:[_tableView performSelectorOnMainThread:@selector(reloadData)withObject:[myparser xmldata] waitUntilDone:NO]; – Pareshkumar 2012-07-23 11:57:07