2013-04-13 30 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。並逐行調試您的項目。並找到你的應用程序。粉碎?我相信它會圍繞任何陣列。

編輯:

我認爲錯在數組名typeList檢查它在cellForRowAtIndexPath方法與斷點。

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

我已經找到一種方法,來解決我的問題。 我只是在Storyboard TableView的XCode屬性中將「Sections」更改爲0。 現在工作正常。

感謝大家的迴應!