找到内存泄漏/过度释放崩溃的来源

时间:2011-05-18 03:46:31

标签: objective-c ios memory-management dealloc

任何人都可以帮我弄清楚我应该发布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];
}

1 个答案:

答案 0 :(得分:3)

首先要做的事情是:您应该将[super dealloc]电话移至dealloc方法的末尾。首先处理你的自定义变量,然后你做的最后一件事是将dealloc推到超类来处理其余的清理工作。


现在,我关注那里的[sortedArray release][sortedArray retain]。为了节省在retain ivar上实现release / sortedArray的语义,您应该做的是为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)