【问题标题】:UI didn't update because of NSOperationQueue waitUntilFinished YESUI 没有更新,因为 NSOperationQueue waitUntilFinished YES
【发布时间】:2012-03-17 05:50:52
【问题描述】:

我遇到了一个问题。场景是这样的:我有一个 NSOperationQueue,其中包含需要 waitUntilDone:YES 的各种 NSOperationQueue。当队列或操作正在运行时,我也需要更新 UI。处理这种情况的最佳方法是什么?

我已经尝试过 performSelectorOnMainThread,但是每次我需要更新 UI 时都需要使用这个方法吗?这似乎不是一个好的解决方案。

- (void)loadPreviewPageWithMagazineID:(NSString *)magazineID userID:(NSString *)userID {
NSMutableArray *operationArray = [NSMutableArray array];
for (NSInteger i = 1; i <= _numTotalPages; ++i) {
    //NSLog(@"currenpage = %d, index = %d",_selectedPage,pageIndex);
    NSDictionary *arguments = [NSDictionary dictionaryWithObjectsAndKeys:magazineID, 
                               @"itemID", userID, @"userID", [NSNumber numberWithInt:i],
                               @"pageNumber", nil];
    AFOperation *imageOperation = 
        [[AFOperation alloc] initWithTarget:self 
                                   selector:@selector(savePageToDisk:) 
                                     object:arguments];
    [imageOperation addObserver:self forKeyPath:@"isFinished" options:0 context:nil];
    [imageOperation setUserInfo:arguments];
    [operationArray addObject:imageOperation];
    [imageOperation release];
}
[_imageQueue addOperations:operationArray waitUntilFinished:YES];
}


- (void)processingMagazine:(NSDictionary *)arguments {
// load pdf document from decrypted data 
NSString *userID = [arguments objectForKey:@"userID"];
NSString *magazineID = [arguments objectForKey:@"itemID"];

[self loadPreviewPageWithMagazineID:magazineID userID:userID];
}

所以每次更新 UI 我都需要调用

[_collectionCoverView performSelectorOnMainThread:@selector(setDownloadProgress:)
                                       withObject:[NSNumber numberWithFloat:progress] 
                                    waitUntilDone:YES];

Is there any appropriate way to handle the UI?

【问题讨论】:

  • 你的意思是说你的队列要等到你更新你的用户界面?
  • 队列和UI可以同时运行吗?
  • 是的。这绝对是可能的。它可能发生。
  • Apple 开发人员参考说,“操作总是在单独的线程上执行,无论它们被指定为并发操作还是非并发操作”。
  • 但是我将 NSOperationQueue 设置为 waitUntilFinished:YES,所以 UI 不会更新。我应该发布代码吗?

标签: objective-c ios nsoperationqueue nsinvocationoperation


【解决方案1】:

我从您的代码中了解不多。但是要完成您想要的,您可以在 AFOperation 方法的末尾添加 UI 更新代码。我的意思是说,如果你在操作方法中添加它,一旦完成一些处理,UI将自动更新。

UI 更新通常也发生在 MainThread。所以调用 performSelectorInMainThread 没有错。

【讨论】:

  • 好的,我想要的是这样的:一个 NSOperationQueue A,NSOperationQueue B。这个 B 队列需要处理一个需要等待完成的进程。然后A addOperation 一个操作B队列的操作,当b队列完成后,我更新UI
  • 所以基本上它就像一个队列操作另一​​个队列(waitUntilFinished:YES)。奇怪的是,当 B 队列运行时,主线程挂起,虽然我已经将它放在另一个队列中。
  • 我想我应该打电话给performSelectorInMainThread。谢谢!
猜你喜欢
  • 2015-07-11
  • 1970-01-01
  • 2016-11-24
  • 1970-01-01
  • 2018-03-13
  • 2019-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多