I do not undserstand why I cannot simply add [sortedArray release]; at the end of this method. Everytime I do, it crashes.
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSString *workoutName = [event.assignedWorkout valueForKey:@"name"];
self.title = workoutName ;
NSMutableArray *sortedArray = [[NSMutableArray alloc]init];
// Sort ExerciseArray
int y = 0;
int x= 0;
do{
if ([[[exerciseArray objectAtIndex:y] index]intValue] == x){
[sortedArray addObject:[exerciseArray objectAtIndex:y] ];
x++;
}
if (y<[exerciseArray count]-1){
y++;
}else {
y=0;
}
}
while(x <= [exerciseArray count]-1);
exerciseArray = sortedArray;
[self.tableView reloadData];
}
If anyone can point me in the right direction or refer me to some documentation, it would be very much appreciated.
You are assigning the array to the
exerciseArrayvariable and then you are releasing the array. The next time you try to access theexerciseArrayvariable, the array will be gone, because assigning it to theexerciseArrayvariable doesn’t increase its retain count.The array object’s retain count is 1 when you first call
alloc. When you assign it to exerciseArray, its retain value is still 1. Then, when you release it, its retain count drops to 0 and you can’t expect to access the array again.You should either not release it (my preference), or else explicitly retain it by calling:
Note the order of those two messages. The first line releases any existing object pointed to by the
exerciseArrayvariable. The second line raises the new array’s retain count to 2, and the second then drops it to 1, so the array is still retained. If you releasesortedArraybefore assigning the new array to theexerciseArrayvariable, the retain count becomes 0 and you will lose it before you can assign it to the new variable.