我正在使用Apple提供的标准代码进行核心数据提取,它在fetch方法的开头有以下语句。
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController_ != nil) {
return fetchedResultsController_;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:self.entityName inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:self.sortFieldName ascending:YES];
NSMutableArray *sortDescriptors = [[NSMutableArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
if(predicate != nil)
[fetchRequest setPredicate:predicate];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:sectionKeyName cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
aFetchedResultsController = nil;
[fetchRequest release];
fetchRequest = nil;
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![fetchedResultsController_ performFetch:&error]) {
}
return fetchedResultsController_;
}
第一次,fetchedResultsController获取所需的信息。但是之后我在这个结果上设置了一个谓词。所以,我希望fetch可以在下次考虑我的谓词。如果它在上面的代码中,它将立即出现,因为旧的值不是nil。
为了解决这个问题,在设置谓词之后,我做了
fetchedResultsController_ = nil;
这样做没问题,但是一旦fetchRequest被分配就会在fetchedResultsController上发生泄漏。
有没有更好的方法来重新执行获取或避免泄漏?
答案 0 :(得分:1)
只需添加一个版本。
if(fetchedResultsController_){
[fetchedResultsController_ release];
}
fetchedResultsController_ = nil;