ShurupuS
ShurupuS

Reputation: 2923

Exception while try to scroll UITableView

I have a very simple app to learn how to work with sections in UITableView but there is an exception -

2013-09-17 08:46:19.956 Sections[4497:c07] * -[__NSArrayI objectAtIndex:]: message sent to deallocated instance 0x9566d40

The whole methods are below - need help.

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"sortednames" ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    self.names = dict;
    NSArray *array = [[_names allKeys] sortedArrayUsingSelector:@selector(compare:)];
    _keys = array;
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    NSLog(@"%lu", (unsigned long)[_keys count]);
    return [_keys count];
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *key = [_keys objectAtIndex:section];
    NSArray *nameSection = [_names objectForKey:key];
    return [nameSection count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];

    NSString *key = [_keys objectAtIndex:section];
    NSArray *nameSection = [_names objectForKey:key];

    static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SectionsTableIdentifier];
    }

    cell.textLabel.text = [nameSection objectAtIndex:row];
    return cell;
}

- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *key = [_keys objectAtIndex:section];
    return key;
}

Upvotes: 0

Views: 105

Answers (2)

Prashant Nikam
Prashant Nikam

Reputation: 2251

Here you are first taking values in other array and then passing it to _keys..thats not proper way of doing it..

just directly pass the values to _keys like below

_keys = [[_names allKeys] sortedArrayUsingSelector:@selector(compare:)];

also check for self.names, you are doing the same thing there.

Hope this will help you.

Upvotes: 1

lykant
lykant

Reputation: 516

You must retain _keys array like that:

_keys = [[[_names allKeys] sortedArrayUsingSelector:@selector(compare:)] retain];

Upvotes: 1

Related Questions