insertRowsAtIndexPaths: withAnimation: создает исключение NSRangeException - PullRequest
4 голосов
/ 12 мая 2011

Это мой код (из учебника по основным данным):

[eventsArray insertObject:event atIndex:0];

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

Третья строка выдает исключение:

2011-05-12 13:13:33.740 Locations[8332:207] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x010145a9 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x01168313 objc_exception_throw + 44
    2   CoreFoundation                      0x0100a0a5 -[__NSArrayM objectAtIndex:] + 261
    3   UIKit                               0x0010d5b3 -[UITableView(_UITableViewPrivate) _endCellAnimationsWithContext:] + 6156
    4   UIKit                               0x000fcd36 -[UITableView insertRowsAtIndexPaths:withRowAnimation:] + 56
    5   Locations                           0x00003462 -[RootViewController addEvent] + 690

Я новичок в разработке для iPhone, и яне могу понять, что это значит.Я вставляю в нулевой индекс tableView, поэтому я понятия не имею, почему он не работает с пустым массивом.Пожалуйста, объясните это мне


stacktrace

eventsArray - массив, из которого я заполняю табличное представление (вероятно. По крайней мере, он используется в cellForRowAtIndexPath)


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // A date formatter for the time stamp.
    static NSDateFormatter *dateFormatter = nil;
    if (dateFormatter == nil) {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    }

    // A number formatter for the latitude and longitude.
    static NSNumberFormatter *numberFormatter = nil;
    if (numberFormatter == nil) {
        numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
        [numberFormatter setMaximumFractionDigits:3];
    }

    static NSString *CellIdentifier = @"Cell";

    // Dequeue or create a new cell.
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    Event *event = (Event *)[eventsArray objectAtIndex:indexPath.row];

    cell.textLabel.text = [dateFormatter stringFromDate:[event creationDate]];

    NSString *string = [NSString stringWithFormat:@"%@, %@",
                        [numberFormatter stringFromNumber:[event latitude]],
                        [numberFormatter stringFromNumber:[event longitude]]];
    cell.detailTextLabel.text = string;

    return cell;
}

Ответы [ 4 ]

3 голосов
/ 23 мая 2011

Была такая же проблема.Просто нужно сказать табличному представлению, что в нем тоже есть 1 раздел.По умолчанию он равен 0, если вы не обновляете его.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}
0 голосов
/ 12 мая 2011

Мне кажется, что ваш eventsArray заполнен и работает, но обновление источника данных tableview не работает должным образом.Это может означать, что источник данных не установлен должным образом, или, возможно, ваши методы источника данных таблицы просмотра возвращают неправильные значения?

Какой код стоит за следующими методами в вашем подклассе?(при условии, что вы правильно соответствуете протоколу UITableViewDataSource).

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
0 голосов
/ 22 мая 2011

Попробуйте добавить это к viewdidLoad в вашем контроллере:

eventsArray = [[NSMutableArray alloc] init];
0 голосов
/ 12 мая 2011

Можете ли вы проверить источник данных, используемый для загрузки табличного представления? Похоже на пустой массив.

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