我在NSManagedObjectContext類中有一個簡單的函數來幫助我從我的moc中獲得結果。我正在執行moc實例提供的performBlockAndWait塊內的結果。我需要返回一個autoreleased數組,並且通常來自moc的executeFetch已經完成了這個。但在這種情況下,即使我用__block指令聲明瞭數組,我仍然需要在塊內部保留數組。它看起來像塊一旦完成就釋放出來。 這是正常的嗎? 謝謝。瞭解塊中的變量(__block指令)
-(NSArray*)executeFetchWithEntityName:(NSString*)entityName predicate:(NSPredicate*)predicate{
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self];
if (!entity) {
NSLog(@"entity is nil in executeFetchWithEntityName: %@", entityName);
return [[[NSArray alloc]init]autorelease];
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
[fetchRequest setEntity:entity];
if(predicate){
[fetchRequest setPredicate:predicate];
}
__block NSError *error = nil;
__block NSArray *array = nil;
[self performBlockAndWait:^{
array = [self executeFetchRequest:fetchRequest error:&error];
[array retain]; <------ IF I DONT RETAIN HERE, IT CRASHES FURTHER ON
}];
NSLog(@"retain count: %i", array.retainCount);
if (error) {
NSLog(@"error");
array = nil;
}
[fetchRequest release];
return [array autorelease];
}
Re。您使用retainCount:http://www.whentouseretaincount.com/ – 2012-03-15 17:19:18
@StephenDarlington - 最後!一個明確的參考鏈接! – jrturton 2012-03-15 17:30:27
jajaja excellent – 2012-03-15 17:45:25