2012-07-24 63 views
2

我得到這段代碼的錯誤。你能幫我弄清楚爲什麼。UITableView dataSource必須從tableView返回一個單元格:cellForRowAtIndexPath錯誤

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"CustomerCell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    Restaurant *restaurant = [self.restaurants objectAtIndex:[indexPath row]]; 
    [[cell textLabel] setText:[NSString stringWithFormat:@"%@ %@",restaurant.Name,restaurant.Address]]; 
    return cell; 
} 

回答

3

與您的代碼問題是,dequeueReusableCellWithIdentifier:並不總是返回給你一個有效的單元格;有時,它返回nil。在這種情況下,您需要分配一個新的單元實例,然後按通常的方式初始化它。就目前而言,如果從dequeueReusableCellWithIdentifier:方法返回一個方法,則您的方法將返回nil

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (!cell) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyle1 reuseIdentifier:CellIdentifier]; 
} 
+0

謝謝,工作完美! – user1426292 2012-07-24 03:20:23

+0

@ user1426292太棒了!如果解決方案適合您,請考慮接受它,讓其他人知道您不再需要積極尋找改進的答案,並在Stack Overflow上獲得全新的徽章。 – dasblinkenlight 2012-07-25 20:15:13

相關問題