2011-07-26 136 views
2

我遇到這個代碼的一個奇怪的問題。從NSMutableArray填充UITableView

- (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] autorelease]; 
    } 


    // Configure the cell... 
    if (accounts != nil) { 
     NSLog(@"Cell: %@", indexPath.row); 
     cell.textLabel.text = [self.accounts objectAtIndex: indexPath.row]; 
    } 
    else 
    { 
     NSLog(@"No cells!"); 
     [cell.textLabel setText:@"No Accounts"]; 
    } 

    return cell; 
} 

我的表視圖填充就好了,除了所有的行包含在我的NSMutableArrayaccounts的第一個項目。我正在記錄indexPath.row的值,並且無論數組中有多少個值,它都會保持爲(null)。我在這裏做錯了什麼?

回答

3

我不相信這個!我正在爲自己爭先恐後地找到答案!

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return [accounts count]; //<--This is wrong!!! 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return 1; // <--This needs to be switched with the error above 
} 

上面的代碼是它在我的數組中打印同一行兩次而不是在我的數組中前進的原因。

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [accounts count]; 
} 

此代碼是正確的,併產生正確的結果。真是太棒了。 ^^;

+0

我剛纔說如果你是cellForRowAtIndexPath只會被調用一次,請檢查你的numberOfRows :) –

2

應該@"%i", indexPath.row@"%@", indexPath.row

此外,我建議把這個在你的方法頂部:

NSUInteger row = [indexPath row]; 

然後你的方法是這樣的:

// Cell Ident Stuff 
// Then configure cell 
if (accounts) { 
    NSLog(@"Cell: %i", row); 
    cell.textLabel.text = [self.accounts objectAtIndex:row]; 
} 
else { 
    NSLog(@"No accounts!"); 
    // Only setting for the first row looks nicer: 
    if (row == 0) cell.textLabel.text = @"No Accounts"; 
} 

這是很好的做法,當處理表格視圖方法。試試看。

+0

我做了這個改變,現在NSLog只報告「Cell:0」。它仍然沒有通過我的陣列前進。 – Tanoro