У меня есть экземпляр класса NSObject, который должен анализировать XML и сохранять NSManagedObjects, он все делает нормально.Но мне нужно получить NSManagedObjectContextDidSaveNotification внутри него, чтобы объединить контексты CoreData.
Дело в том, что мой экземпляр освобождается раньше, чем я получаю уведомление выше.
Как я могу предотвратить мой экземпляросвобожден раньше?
Вот когда я вызываю свой экземпляр
// in my ViewController implementation
WSNoticia *wsNoticia = [WSNoticia new]; // __strong by default right?
Вот реализация WSNoticia:
</p>
<pre><code>- (id)init {
self = [super init];
if (self) {
[self parseNews];
}
return self;
}
- (void)dealloc {
// called before mergeChanges: or updateContext:
}
#pragma mark - Private Methods
- (void)parseNews {
// save context in another thread
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
[context setUndoManager:nil]; // performance benefit
[context setPersistentStoreCoordinator:[appDelegate persistentStoreCoordinator]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mergeChanges:) name:NSManagedObjectContextDidSaveNotification object:context];
NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{
// fetching things
}];
[blockOperation setCompletionBlock:^{
// updating and saving things
// here the NSManagedObjectContextDidSaveNotification is called (by doing [context save:nil];
}];
// add operation to queue
NSOperationQueue *operationQueue = [NSOperationQueue new];
[operationQueue addOperation:blockOperation];
}
// doesn't get called
- (void)updateContext:(NSNotification *)notification {
NSManagedObjectContext *mainContext = [self managedObjectContext];
[mainContext mergeChangesFromContextDidSaveNotification:notification];
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationNameNoticiasParsed object:self];
}
#pragma mark - NSNotificationCenter
// doesn't get called
- (void)mergeChanges:(NSNotification *)notification {
[[NSNotificationCenter defaultCenter] removeObserver:self];
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *mainContext = [appDelegate managedObjectContext];
if ([notification object] == mainContext) {
// main context save, no need to perform the merge
return;
}
[self performSelectorOnMainThread:@selector(updateContext:) withObject:notification waitUntilDone:YES];
}