Declared and synthesized NSArray works in all methods but one

I have an array of NSMutableDictionaries which has been sorted.

This array has been declared and synthesized so that its reachable anywhere in the code. However, its not.

When I try to read it out in cellForRowAtIndexPath, I get 0x5852400 does not appear to point to a valid object in debugger by using the po command, and I get the EXC_BAD_ACCESS error when using NSLog.

Code:

- (void)request:(FBRequest *)request didLoad:(NSArray*)result
{
    int counter;
    friendsArray = [[NSMutableArray alloc] init];

    for (NSDictionary *d in [result objectForKey:@"data"])
    {   
        [friendsArray addObject:d];
        counter++;
    }

    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"first_name" ascending:YES] autorelease];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    NSArray *sortedArray;

    newfriendsArray = [[NSArray alloc] init];

    newfriendsArray = [friendsArray sortedArrayUsingDescriptors:sortDescriptors];

    NSLog(@"The new array which works and has been sorted: %@", newfriendsArray);

    [[self tableView] reloadData];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.

    NSLog(@"Array still working here: %@", newfriendsArray);

    return [newfriendsArray count];
}

Doing the same NSlog like the ones above in cellForRowAtIndexPath will cause the simulator to crash.

Answers


It's a memory management error. In this line:

newfriendsArray = [friendsArray sortedArrayUsingDescriptors:sortDescriptors];

sortedArrayUsingDescriptors: returns an autoreleased object that you need to retain if you want to use it for longer than the current method. The line above:

newfriendsArray = [[NSArray alloc] init];

has no effect other than introduce a memory leak to your code. It seems you have not quite understood when you need to create new objects and when other methods do this for you. In addition, you should really use properties to set your ivars (self.newFriendsArray = ...;) to avoid these simple memory management errors.


Need Your Help

C++ interview preparation

c++ logic

I have a Phone interview coming up next with with a company which works in financial software industry. The interview is mainly going to be in C++ and problem solving and logic. Please tell me the ...

Array of arrays to object in javascript

javascript jquery

I am trying to make an array which then contains mutiple arrays (which are added in the each loop) and then pass the information to ajax to post off.