cellForRowAtIndexPath:indexPath始终等于0

时间:2011-08-02 11:54:31

标签: ios

我不明白。 cellForRowAtIndexPath函数的indexPath参数始终为0.我的表中当前有7行。我的表显示的是第一个表行的7倍。什么可能导致indexPath始终为零?

@implementation SitesViewController

@synthesize sites, siteCell;

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SiteCell"];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"SiteCell" owner:self options:nil];
        cell = siteCell;
        self.siteCell = nil;
    }
    Site *site = [sites objectAtIndex:indexPath.section];
    UILabel *siteNameLabel;
    siteNameLabel = (UILabel *)[cell viewWithTag:1];
    siteNameLabel.text = site.siteName;

    return cell;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSManagedObjectContext *context = [[DigMateAppDelegate sharedAppDelegate] managedObjectContext];
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Sites" inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDesc];
    NSError *error;
    sites = [context executeFetchRequest:request error:&error];
}

1 个答案:

答案 0 :(得分:8)

由于你有7行,我假设有1个部分,那么你应该根据行索引从数组中获取记录,而不是部分。所以cellForRowAtIndexPath:方法中的以下行:

Site *site = [sites objectAtIndex:indexPath.section];

应该是:

// Use indexPath's row instead of section!
Site *site = [sites objectAtIndex:indexPath.row];