您的长期运行的操作应移至 NSOperation 子类
AhmedsOperation.h
@interface AhmedsOperation : NSOperation
@end
AhmedsOperation.m
@implementation AhmedsOperation
// You override - (void)main to do your work
- (void)main
{
for (int i = 0; i < 1000; i++) {
if ([self isCancelled]) {
// Something cancelled the operation
return;
}
sleep(5);
// Emit a notification on the main thread
// Without this, the notification will be sent on the secondary thread that we're
// running this operation on
[self performSelectorOnMainThread:@(sendNotificationOnMainThread:)
withObject:[NSNotification notificationWithName:@"MyNotification"
object:self
userInfo:nil]
waitUntilDone:NO];
}
}
- (void)sendNotificationOnMainThread:(NSNotification *)note
{
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotification:note];
}
然后在您的主代码中,当您想要执行操作时,您只需创建一个 AhmedsOperation 对象,并将其推送到 NSOperationQueue 并收听通知。
AhmedsOperation *op = [[AhmedsOperation alloc] init];
NSOperationQueue *defaultQueue = [MLNSample defaultOperationQueue];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(progressUpdateNotification:)
name:@"MyNotification"
object:op];
[defaultQueue addOperation:op];