0

我有一个 EventObject(s) 数组。每个对象都有标题和城市以及许多其他属性。我想将单元格的标题显示为事件标题,将单元格的副标题显示为事件城市。我尝试在下面这样做,但我只显示最后一个对象 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];
    }
4

1 回答 1

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;
}
于 2013-03-27T16:13:16.917 回答