[iOS] NSOperationQueue をシングルトンで扱う方法

Tadashi Shigeoka ·  Thu, May 2, 2013

NSOperationQueue をシングルトンで扱うために下記のように NSOperationQueue+SharedQueue.h と NSOperationQueue+SharedQueue.m を追加します。

//  NSOperationQueue+SharedQueue.h

#import 

@interface NSOperationQueue (SharedQueue)

+ (NSOperationQueue *) sharedOperationQueue;
- (void)performSelectorOnBackgroundQueue:(SEL)aSelector withObject:(id)anObject;

@end

#define SHARED_OPERATION_QUEUE [NSOperationQueue sharedOperationQueue]
//  NSOperationQueue+SharedQueue.m

#import "NSOperationQueue+SharedQueue.h"

@implementation NSOperationQueue (SharedQueue)

+ (NSOperationQueue *) sharedOperationQueue {
    
    static dispatch_once_t pred;
    static NSOperationQueue* sharedQueue;
    
    dispatch_once(&pred, ^{
        sharedQueue = [[NSOperationQueue alloc] init];
    });
    
    return sharedQueue;
}

- (void) performSelectorOnBackgroundQueue:(SEL)aSelector withObject:(id)anObject {
    
    NSOperation* operation = [[NSInvocationOperation alloc]
                              initWithTarget:self
                              selector:aSelector
                              object:anObject];
    [[NSOperationQueue sharedOperationQueue] addOperation:operation];
    [operation release];
}

@end

[参考]

iphone - Sharing NSOperationQueue across View Controllers? - Stack Overflow

Tutorial: Asynchronous HTTP Client Using NSOperationQueue | iPhone Programming Tutorials

objective c - Global NSOperationQueue - Stack Overflow

Cocoa Tutorial: NSOperation and NSOperationQueue | Cocoa Is My GirlfriendCocoa Is My Girlfriend

Library/NSOperationQueue+SharedQueue.h at master · docchang/Library · GitHub

Library/NSOperationQueue+SharedQueue.m at master · docchang/Library · GitHub