0

i have in my code like this :

- (id)init
{
   self = [super initWithNibName:nibName bundle:nil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(userDataDidUpdate)
                                                     name:NSManagedObjectContextDidSaveNotification
                                                   object:[UserData managedObjectContext]];
    }
    return self;
}

- (void)userDataDidUpdate
{
   // notification received...
}

and in an other class ( CoreData manager) i am doing like this :

[[UserData managedObjectContext] performBlock:^{

                     NSError *error;
                     if (![[UserData managedObjectContext] save:&error])
                     {
                         // handle error
                     }

                     isSyncing = NO;
                     [[NSNotificationCenter defaultCenter] postNotificationName:NDUserDataSyncDidUpdateLocalData object:nil];

                     }];

The problem is that i send the notification in the performBlock of the managed objectContext and it's not the main thread. How can i send the notification inside the performBlcok in the main thread ?

Thanks

4

2 回答 2

0

这两个片段有什么关系?注册/发送了不同的通知。

无论如何,您可以执行以下操作:

dispatch_async(dispatch_get_main_queue(), ^{
    [[NSNotificationCenter defaultCenter] postNotificationName:NDUserDataSyncDidUpdateLocalData object:nil];        
});

PS 我希望你在 dealloc 方法中从通知中心删除观察者。

于 2013-10-17T10:03:05.870 回答
0

使用 GCD 很简单,只需像这样包装它:

dispatch_sync(dispatch_get_main_queue(), ^{
  [[NSNotificationCenter defaultCenter] postNotificationName:NDUserDataSyncDidUpdateLocalData object:nil];
});

请注意,我dispatch_sync在这里使用而不是dispatch_async,因为您通常希望在从调用返回之前完全处理您的通知postNotificationName:...

于 2013-10-17T10:04:15.797 回答