我开始在Instruments中测试我的应用程序来清理任何内存泄漏。我已经能够清除除Core Data之外的所有内存泄漏。乐器总是指向我这段代码:
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error
}
我使用以下代码在头文件中声明了managedObjectContext:
@interface UpperBody : UITableViewController <UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITableView *upperTable;
NSMutableArray *exercises;
NSManagedObjectContext *managedObjectContext;
}
@property (nonatomic, retain) NSMutableArray *exercises;
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
我在(void)dealloc部分中释放了managedObjectContext。以下是使用managedObjectContext的完整代码部分:
- (void)loadExercises {
if (managedObjectContext == nil) {
managedObjectContext = [(iFitAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Exercises" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category == 1"];
[request setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"exerciseName" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error
}
[self setExercises:mutableFetchResults];
// [exercises addObject:@"Add Exercise"];
NSLog(@"Count of exercises %i", exercises.count);
[mutableFetchResults release];
[request release];
[self.tableView reloadData];
}
任何关于可能导致泄漏的建议都将不胜感激!提前谢谢!
答案 0 :(得分:0)
k我上面的代码可能有泄漏。我通过在需要时使用指向一个指针来声明NSManagedObjectContext。以下是代码示例:
iFitAppDelegate *appDelegate = (iFitAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
这解决了我的泄漏,所以它必须与我如何分配和释放NSManagedObjectContext有关。谢谢指点,@ albertamg!