检测performSelectorInBackground的结束:withObject:

时间:2011-03-23 14:32:00

标签: iphone multithreading ios detect nsthread

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

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

如何检测此操作的结束?

4 个答案:

答案 0 :(得分:15)

在doSomething方法结束时拨打电话?!

- (void)doSomething {
    // Thread starts here

    // Do something

    // Thread ends here
    [self performSelectorOnMainThread:@selector(doSomethingDone) withObject:nil waitUntilDone:NO];
}

答案 1 :(得分:1)

如果您只想知道它何时完成(并且不想传回大量数据 - 此时我会推荐一位代表),您只需向通知中心发布通知即可。

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

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

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

并在dealloc中添加:

[[NSNotificationCenter defaultCenter] removeObserver:self];

答案 2 :(得分:0)

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

答案 3 :(得分:0)

我有一个我创建的通用后台处理程序来解决这个问题。只有第一种方法是公开的,所以它可以在整个过程中使用。请注意,所有参数都是必需的。

+(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;
    }];