Несколько разделов в UITableView, вызывающих NSRangeException? - PullRequest
0 голосов
/ 24 января 2012

Я делаю простое тестовое приложение для навигации по дереву категорий.Всякий раз, когда я пытаюсь разбить табличное представление на несколько разделов, я получаю SIGABRT без полезного стека вызовов, и это:

Завершение приложения из-за необработанного исключения 'NSRangeException', причина: '***- [__ NSArrayI objectAtIndex:]: индекс 1 за пределами [0 .. 0] '

Я установил контрольные точки почти везде.Все работает правильно, когда numberOfSectionsInTableView возвращает 1, но когда он возвращает 2, это все, что он получает - никакие другие контрольные точки не достигнуты.Я установил точку останова при каждом звонке, который я делаю, на objectAtIndex, и я понятия не имею, в чем проблема.

Вот мой код реализации:

//
//  MasterViewController.m
//  Vingo
//
//  Created by ryan on 12-01-23.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MasterViewController.h"
#import "LinkViewController.h"

@implementation MasterViewController

@synthesize detailViewController = _detailViewController;

- (void)awakeFromNib
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        self.clearsSelectionOnViewWillAppear = NO;
        self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
    }
    [super awakeFromNib];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionMiddle];
    }

    self.navigationController.navigationBar.tintColor = [UIColor orangeColor];

    categories = [NSArray arrayWithObjects:[[VingoCategory alloc] initWithId:0 andName:@"A category"], nil];
    links = [NSArray arrayWithObjects:[[VingoLink alloc] initWithId:0 andName:@"A link"], nil];
    //links = [NSArray array]; // works
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

#pragma mark - Table data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [categories count] && section == 0 ?
            [categories count]
        :   [links count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if([categories count]) {
        if([links count]) {
            return 2;
        }

        return 1;
    }

    if([links count]) {
        return 1;
    }

    return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [categories count] && section == 0 ?
            @"Categories"
        :   @"Links";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"Cell";

    // Try to get a reusable cell:
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

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

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    if([categories count] && indexPath.section == 0) {
        NSLog(@"Looking for item %d in categories", indexPath.row);
        VingoCategory *category = [categories objectAtIndex:indexPath.row];
        cell.textLabel.text = category.name;
        cell.textLabel.tag = category.id;
    } else {
        NSLog(@"Looking for item %d in links", indexPath.row);
        VingoLink *link = [links objectAtIndex:indexPath.row];
        cell.textLabel.text = link.name;
        cell.textLabel.tag = link.id;
    }

    return cell;
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if([categories count] && indexPath.section == 0) {

    } else {
        LinkViewController *linkController = [[LinkViewController alloc] init];
        VingoLink *link = [links objectAtIndex:indexPath.row];
        linkController.navigationItem.title = link.name;
        [self.navigationController pushViewController:linkController animated:YES];
    }

    return indexPath;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

@end

Может кто-нибудьнайти проблему?Я надеюсь, что это что-то очевидное, что я пропускаю, и это не серьезная проблема.

Моя инициализация для двух идентичных NSArray s в viewDidLoad.

1 Ответ

0 голосов
/ 25 января 2012

Мое лучшее предположение, что вы не добавляете новые разделы и строки?

См. UITableView * insertSections: и insertRowsAtIndexPaths:

Конечно, вы можете делать это в другом месте, и я не понимаю этого ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...