从NSOperation重新加载UITableView



我已经编写了以下代码来从NSInvocationOperation重新加载UITableView。然而,在调用[tableview reloadData]之后,接口在很长一段时间内都不会更新。

苹果公司的文档中说,NSOperation中不会调用委托方法。

NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
                                            initWithTarget:self
                                            selector:@selector(connectToServer)
                                            object:nil];
[queue addOperation:operation];
[operation release];
[queue autorelease];
- (void) connectToServer
{
    ...
    ...
    [tableview reloadData];
}

问题是UI更新必须发生在主线程上,而reloadData是通过NSOperationQueue从后台线程调用的。

您可以使用NSObject方法performSelectOnMainThread:withObject:waitUntilDone:来确保在主线程上发生此类更新。

- (void) connectToServer
{
    ...
    ...
    [tableView performSelectorOnMainThread:@selector(reloadData)
            withObject:nil
            waitUntilDone:NO];
}

此外,NSOperationQueue不应该是局部变量。它应该是此类的保留属性,并且仅在dealloc中发布。

最新更新