0

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;
}
4

2 回答 2

1

你必须保留_keys这样的数组:

_keys = [[[_names allKeys] sortedArrayUsingSelector:@selector(compare:)] retain];
于 2013-09-17T04:59:43.987 回答
1

在这里,您首先在其他数组中获取值,然后将其传递给 _ keys..这不是正确的做法..

只需直接将值传递给 _keys,如下所示

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

还要检查self.names,你在那里做同样的事情。

希望这会帮助你。

于 2013-09-17T05:05:33.993 回答