我有一个异步服务器请求我的iOS应用:检测performSelectorInBackground结束:withObject:
[self performSelectorInBackground:@selector(doSomething) withObject:nil];
我如何可以检测到这种操作的结束?
我有一个异步服务器请求我的iOS应用:检测performSelectorInBackground结束:withObject:
[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];
}
您可能希望让您的doSomething选择器在完成自己时发回。 performSelectorInBackground上发生的事情在API的内部,如果您想要更多控制,您可能需要使用performSelector:onThread:withObject:waitUntilDone:
并定期检查传递线程上的isFinished
。我相信你更关心doSomething比实际的线程完成,所以只是从那里回来。
如果您只是想知道何时完成(并且不想传回大量数据 - 在哪一点上,我会推荐一位代表),您只需将通知发布到通知中心即可。
[[NSNotificationCenter defaultCenter] postNotificationName:kYourFinishedNotificationName object:nil];
您的视图控制器viewDidLoad方法中添加
:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(yourNotificationListenerMethod:)
name:kYourFinishedNotificationName
object:nil];
和dealloc的范围内,添加:
[[NSNotificationCenter defaultCenter] removeObserver:self];
我有我创建了解决该问题的一般背景处理程序。只有第一种方法是公开的,因此可以在整个过程中使用。请注意,所有参数都是必需的。
+(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;
}];
这是规范的方法,但最近我一直认为,如果你明确地编码到后台线程,你的可能做错了事情(或者至少“困难的方式”)。大多数阻塞主线程的东西都有一个异步方法,可以使用回调块或委托方法来处理结果。 – 2011-03-23 14:40:39
thx :-)正常工作:-)) – cuSoon 2011-03-23 14:43:39