检测performSelectorInBackground的结束:withObject:

我有我的iOS应用程序中的asynchronous服务器请求:

[self performSelectorInBackground:@selector(doSomething) withObject:nil]; 

我怎样才能检测到这个操作的结束?

在doSomething方法的末尾打个电话?

 - (void)doSomething { // Thread starts here // Do something // Thread ends here [self performSelectorOnMainThread:@selector(doSomethingDone) withObject:nil waitUntilDone:NO]; } 

如果你只是想知道什么时候完成(而不想传回太多的数据 – 那么我会推荐一个委托),你可以简单地通知通知中心。

 [[NSNotificationCenter defaultCenter] postNotificationName:kYourFinishedNotificationName object:nil]; 

在您的视图控制器viewDidLoad方法中添加:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourNotificationListenerMethod:) name:kYourFinishedNotificationName object:nil]; 

在dealloc中,添加:

 [[NSNotificationCenter defaultCenter] removeObserver:self]; 

你可能想让你的doSomethingselect器在它自己完成时发回。 performSelectorInBackground上发生的事情是API的内部,如果你想要更多的控制,你可能想使用performSelector:onThread:withObject:waitUntilDone:并定期检查传递给线程的isFinished 。 我相信你更关心doSomething比实际的线程完成,所以只是从那里回来。

我有一个一般的背景处理程序,我创build了解决这个问题。 只有第一种方法是公开的,因此可以在整个过程中使用。 请注意,所有参数都是必需的。

 +(void) Run: (SEL)sel inBackground: (id)target withState: (id)state withCompletion: (void(^)(id state))completionHandler // public { [(id)self performSelectorInBackground: @selector(RunSelector:) withObject: @[target, NSStringFromSelector(sel), state, completionHandler]]; } +(void) RunSelector: (NSArray*)args { id target = [args objectAtIndex: 0]; SEL sel = NSSelectorFromString([args objectAtIndex: 1]); id state = [args objectAtIndex: 2]; void (^completionHandler)(id state) = [args objectAtIndex: 3]; [target performSelector: sel withObject: state]; [(id)self performSelectorOnMainThread: @selector(RunCompletion:) withObject: @[completionHandler, state] waitUntilDone: true]; } +(void) RunCompletion: (NSArray*)args { void (^completionHandler)(id state) = [args objectAtIndex: 0]; id state = [args objectAtIndex: 1]; completionHandler(state); } 

这是一个如何调用的例子:

 NSMutableDictionary* dic = [[NSMutableDictionary alloc] init]; __block BOOL done = false; [Utility Run: @selector(RunSomething:) inBackground: self withState: dic withCompletion:^(id state) { done = true; }];