2012-05-28 52 views
0

我從一個節的tableview開始,第一節總是有三行。一些內容已經下載完成後,我想展現出新的細胞,在第二部分,所以我做的:在新節中的表格視圖中插入一行

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

但我得到一個NSInternalConsistencyException:

終止應用程序由於未捕獲的異常 「NSInternalInconsistencyException ',原因:'無效更新:無效 部分數量。更新(2)後表 視圖中包含的部分數量必須等於更新(1)之前的表視圖中包含的部分 的數目,加或減 插入或刪除的部分數目(0插入,0刪除)。'

爲什麼不自動插入新節,如果插入節,插入不在新節的行時會出現問題。

爲什麼不能自動添加新的部分?當然,InsertRowAtIndexpath:如果需要,還包括插入節,因爲NSIndexPath也包含節。

回答

3
[self.tableView insertSections:nsIndexSetToInsert withRowAnimation:UITableViewRowAnimationAutomatic]; 

並且不要忘記相應地設置numberOfSectionsInTavleView和numberOfRowsInSection。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    NSInteger numberOfSections; 
    if (condition1) { 
     numberOfSections = 2; 
    } else if (condition2) { 
     numberOfSections = 3; 
    } else { 
     numberOfSections = 4; 
    } 

    return numberOfSections; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section 
    if(section == 1) return 3; 
    else return numberOfRows; 
} 
+0

我已經完成了第一行代碼,其餘的按預期工作(否則不會拋出異常,至少不會出現給出的錯誤),並且如果我插入需要新的行部分,但是如果在現有部分中插入一行,就會崩潰 –

+0

Jonathan,你究竟是什麼意思「我已經完成了第一行代碼」和「其餘部分按預期工作」。基本上,這個答案告訴你,你有責任爲numberOfSectionsInTableView:和tableView:numberOfRowsInSection:正確returninv值。如果插入新的部分,則前者必須正確地返回新值,並且如果在現有部分中插入一行,則後者必須反映該更改。您必須將數據綁定到嘗試更新tableView。這是你的意思是「我已經完成了第一行代碼」和「休息正在按預期工作」? –

0

一旦你的內容從服務器下載,請記住這viewDidLoad中

childArray1 = [[NSMutableArray alloc] initWithObjects: @"Apple", @"Microsoft", @"HP", @"Cisco", nil]; 
childArray2 = [[NSMutableArray alloc] init]; 
parentArray = [[NSMutableArray alloc] initWithObjects:childArray1, nil]; 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return [parentArray count]; 
} 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
     NSInteger rowCount ; 
     if (section == 0) 
     { 
      rowCount = [childArray1 count]; 
     } 
     else 
     { 
      rowCount = [childArray2 count]; 
     } 
     return rowCount; 
} 

if([childArray2 count] > 0) 
    [parentArray addObject : childArray2]; 
[tableView reloadData]; 

這應該適合你。