目标 c - 查找内存泄漏/过度释放 crach 的来源



谁能帮我弄清楚我应该在哪里发布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];

您现在可以删除releaseretain调用,因为这会自动处理。确保在dealloc方法中添加一行以清理变量。

self.sortedArray = nil;

..这将为您调用阵列上的release

编辑:这也适用于exerciseArray,这是您的实际问题。只要涉及 Cocoa 类,您就可以使用 @property (retain)@synthesize 简化内存管理。对于NSInteger和其他基元类型,或者当您不想持有对该对象的拥有引用时,请改用 @property (assign)

最新更新