最后一条记录显示在所有行中

时间:2013-03-27 15:44:05

标签: ios objective-c

我有一个EventObject数组。每个对象都有标题和城市以及许多其他属性。我希望将单元格的标题显示为事件标题,将单元格的字幕显示为事件城市。我尝试在下面这样做,但我只得到最后一个显示4次的对象(即数组中的对象数)。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

//    NSDate *object = _objects[indexPath.row];
//    cell.textLabel.text = [object description];

    EventObject *eventInstance = [[EventObject alloc] init];
    int row = [indexPath row];

    eventInstance = eventObjectsArray[row];
    cell.textLabel.text = eventInstance.eventTitle;
    NSLog(@"Event Title: %@", eventInstance.eventTitle);
    cell.detailTextLabel.text = eventInstance.eventCity;

    return cell;
}

我做错了什么?我正在学习Objective-c,所以初学者肯定会有错误。谢谢

编辑:这是我插入对象的方式:

 //get events from database
    eventsDictionary = [eventInstance getEventsObjects];

    //process each key in dictionary and assign to eventInstance
    for(id key in eventsDictionary)
    {
         eventInstance.eventId = [NSString stringWithFormat:@"%@", key[@"id"]];
         eventInstance.eventTitle = [NSString stringWithFormat:@"%@", key[@"title"]];
         eventInstance.eventDescription = [NSString stringWithFormat:@"%@", key[@"description"]];
         eventInstance.eventCity = [NSString stringWithFormat:@"%@", key[@"city"]];
         [eventObjectsArray addObject:eventInstance];
    }

1 个答案:

答案 0 :(得分:1)

<强>建议

[这可能是问题]

在eventObjectsArray中添加对象时,确保每次添加对象之前都有新的EventObject声明

EventObject *eventInstance = [[EventObject alloc] init];
eventInstance.eventTitle = @"your title";
eventInstance.eventCity  = @"your city";
[eventObjectsArray addObject:eventInstance];

[这是建议,因为您应该知道这可以改善您的编码标准和内存管理]

从数组中重新获取对象时,你真的不需要拥有自定义对象的实例,而不是像

那样对它有所了解
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    //EventObject *eventInstance = [[EventObject alloc] init]; //you don't need this
    int row = [indexPath row];

    EventObject *eventInstance = eventObjectsArray[row]; // make reference like this
    cell.textLabel.text = eventInstance.eventTitle;
    NSLog(@"Event Title: %@", eventInstance.eventTitle);
    cell.detailTextLabel.text = eventInstance.eventCity;

    return cell;
}