2011-07-26 139 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