2013-04-13 3 views
0

У меня есть редактируемый UITableView (с добавлением и удалением элементов) в моем приложении. Это работает странно.
Пока у меня есть только одна или две строки, все работает отлично. Но если я добавлю больше предметов, у меня есть исключение '*** -[__NSArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 2]'Странное поведение UITableView при редактировании

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

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    int plusRow = 0; 
    if ([[self tableView] isEditing]) plusRow = 1; 

    return [typeList count] + plusRow; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

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

    if ([indexPath row] > ([typeList count]-1)) { 
     NSString * appendCellDescription = @""; 

     if ([[self tableView] isEditing]) appendCellDescription = @"Add"; 

     [[cell textLabel] setText:appendCellDescription]; 
    } else { 
     NSLog(@"Accessing array: %d", [indexPath row]); 
     [[cell textLabel] setText:[[typeList getObject:[indexPath row]] description]]; 
    } 

    return cell; 
} 

#pragma mark - Editing table view 

- (UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    NSLog(@"Row: %d, count: %d", [indexPath row], [typeList count]); 

    if (indexPath.row > [typeList count]-1) { 
     return UITableViewCellEditingStyleInsert; 
    } else { 
     return UITableViewCellEditingStyleDelete; 
    } 
} 

- (IBAction)btnModifyClick:(id)sender{ 
    if ([[self tableView] isEditing]) { 
     [[self tableView] setEditing:FALSE animated:YES]; 
     [[self tableView] reloadData]; 
    } else { 
     [[self tableView] setEditing:TRUE animated:YES]; 
     [[self tableView] reloadData]; 
    } 
} 
+0

Какой тип 'typeList'? Я думал, что это 'NSArray', но вызов' [typeList getObject: [indexPath row]] 'вызывает у меня сомнения. Где вызов 'objectAtIndex:', во всяком случае? – dasblinkenlight

+0

Это не NSArray, это пользовательский класс, основанный на NSObject с методом getObject ... это работает нормально. – Andrey

ответ

0

Вообще Эта ошибка описания, когда ошибка в индексе массива, такие как вас массив есть 3 пункта, и вы Тринг, чтобы получить/абстрактный 4-ый элемент из массива, в то время этого типа ошибки генерации.

Лучший способ поиска ошибок использовать BreakPint. и отлаживать проект за строкой. и найдите, где ваше приложение. раздавить ??? Я уверен, что он крутится вокруг любого массива.

EDIT:

Я считаю ошибку в имени массива typeList проверить его в cellForRowAtIndexPath методе с BreakPoint.

0

numberOfRowsInSection возвращает большее количество элементов подсчитывать, чем один неправдоподобные в cellForRowAtIndexPath методы источника данных, попробуйте отладки возвращаемого значения:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    int plusRow = 0; 
    if ([[self tableView] isEditing]) plusRow = 1; 
    NSLog(@"%i",[typeList count] + plusRow); 
    return [typeList count] + plusRow; 
} 
0

Я нашел способ, чтобы решить мою проблему. Я только что изменил «Разделы» на 0 в свойствах XCode в раскадровке TableView. И теперь работает нормально.

Спасибо всем за ответ!

Смежные вопросы