我已经sublcassed一个NSOperation并设置我的completionBlock,但它似乎永远不会进入,即使当操作完成。这里是我的代码:为什么我的completionBlock永远不会在NSOperation中调用?
目录控制器类树立的NSOperation:
- (void)setupOperation {
...
ImportWordOperation *importWordOperation = [[ImportWordOperation alloc] initWithCatalog:words];
[importWordOperation setMainObjectContext:[app managedObjectContext]];
[importWordOperation setCompletionBlock:^{
[(ViewController *)[[app window] rootViewController] fetchResults];
}];
[[NSOperationQueue mainQueue] addOperation:importWordOperation];
[importWordOperation release];
...
}
正如你所看到的,我设置完成块主线程上执行的方法,在一些其他的控制器。
然后,在main
我的子类NSOperation类:ImportWordOperation.m
,我启动后台操作。我甚至为了推翻isFinished
伊娃才会触发完成方法:
- (void)setFinished:(BOOL)_finished {
finished = _finished;
}
- (BOOL)isFinished {
return (self.isCancelled ? YES: finished);
}
- (void)addWords:(NSDictionary *)userInfo {
NSError *error = nil;
AppDelegate *app = [AppDelegate sharedInstance];
NSManagedObjectContext *localMOC = [userInfo valueForKey:@"localMOC"];
NSEntityDescription *ent = [NSEntityDescription entityForName:@"Word" inManagedObjectContext:localMOC];
for (NSDictionary *dictWord in [userInfo objectForKey:@"words"]) {
Word *wordN = [[Word alloc] initWithEntity:ent insertIntoManagedObjectContext:localMOC];
[wordN setValuesForKeysWithDictionary:dictWord];
[wordN release];
}
if (![[userInfo valueForKey:@"localMOC"] save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
[localMOC reset];
[self setFinished:YES];
}
- (void)main {
finished = NO;
NSManagedObjectContext *localMOC = nil;
NSUInteger type = NSConfinementConcurrencyType;
localMOC = [[NSManagedObjectContext alloc] initWithConcurrencyType:type];
[localMOC setUndoManager:nil];
[localMOC setParentContext:[self mainObjectContext]];
if (![self isCancelled]) {
if ([self.words count] > 0) {
[self performSelectorInBackground:@selector(addWords:) withObject:@{@"words":self.words, @"localMOC":localMOC}];
}
}
}
如果我删除isFinished存取方法,然后完成块被调用但在此之前的方式ImportWordOperation
结束。
我读过的代码使用了它自己的完成块,但是NSOperation子类中的完成块有什么用处?
任何想法或指向类似的解决情况将不胜感激。
感谢!这是'main' /'start'方法。我需要实现'start'而不是'main',因为我需要它是并发的。我改变了这一点,并调整了setFinished KVO,它的工作!我正在添加'-cancel'方法来整理事情。 – 2013-03-26 17:08:05