使用带导入选择器的notificationcenter

时间:2014-12-23 16:20:47

标签: macos cocoa notifications

我想从notificationcenter获取非主线程的通知。 有什么方法可以在将观察者添加到NotificationCenter时使用performselector onThread吗?

1 个答案:

答案 0 :(得分:1)

您必须使用要处理通知的NSOperationQueue设置dispatch_queue_t。以下是注册当前区域设置更改通知的示例:

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        //You need to set this variable to the queue you want the blocks to run on if not on default background queue
        dispatch_queue_t queueToPostTo = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

        //Properties being used
        //@property (nonatomic, strong) NSObject * localeChangeObserver;
        //@property (nonatomic, strong) NSOperationQueue * localChangeObserverQueue;

        self.localChangeObserverQueue = [[NSOperationQueue alloc] init];
        [self.localChangeObserverQueue setUnderlyingQueue:queueToPostTo];

        NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter];
        self.localeChangeObserver =  [notificationCenter addObserverForName:NSCurrentLocaleDidChangeNotification
                                                                     object:nil
                                                                      queue:self.localChangeObserverQueue
                                                                 usingBlock:^(NSNotification *note) {
                                                                     //Your code here for processing notification. 
                                                                 }];
    }
    return self;
}
- (void)dealloc
{
    NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self.localeChangeObserver];
}