長時間実行する操作は、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];