谁能帮我弄清楚我应该在哪里发布exerciseArray
?我在dealloc
和在打电话之前发布时遇到了崩溃sortedArray
.此代码被多次调用。
//Set exerciseArray
review.exerciseArray = [[workout assignedExercises] allObjects];
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(@"viewWillAppear");
NSString *workoutName = [event.assignedWorkout valueForKey:@"name"];
self.title = workoutName ;
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"index"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[sortedArray release];
sortedArray= [exerciseArray sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"*****SORTEDARRAY****** %d",[sortedArray retainCount]);
for (Exercise *ex in sortedArray){
NSLog(@"%@ %@ %@",ex.name , ex.repCount, ex.weight);
}
NSLog(@"*********************");
[sortedArray retain];
[self.tableView reloadData];
}
- (void)dealloc {
[super dealloc];
[managedObjectContext release];
[event release];
}
首先:您应该将[super dealloc]
调用移动到dealloc
方法的末尾。首先处理自定义变量,然后最后一件事是将dealloc
推送到超类以处理其余的清理。
现在,我担心那里的[sortedArray release]
和[sortedArray retain]
。为了节省在sortedArray
ivar上实现retain
/release
的语义,您应该做的是为sortedArray
声明一个属性,如下所示:
// this goes in your @interface
@property (nonatomic, retain) NSArray *sortedArray;
// this goes in your @implementation
@synthesize sortedArray;
现在,您可以轻松设置sortedArray
,而无需担心保留或释放:
// note the use of self, this is required
self.sortedArray = [exerciseArray sortedArrayUsingDescriptors:sortDescriptors];
您现在可以删除release
和retain
调用,因为这会自动处理。确保在dealloc
方法中添加一行以清理变量。
self.sortedArray = nil;
..这将为您调用阵列上的release
。
编辑:这也适用于exerciseArray,这是您的实际问题。只要涉及 Cocoa 类,您就可以使用 @property (retain)
和 @synthesize
简化内存管理。对于NSInteger
和其他基元类型,或者当您不想持有对该对象的拥有引用时,请改用 @property (assign)
。