iOS TableView 在每个单元格中显示相同的对象

标签 ios objective-c nsmutablearray uitableview

我有一个奇怪的问题,我正在设置一个非常基本的 TableView 来显示联系人,我有如下所示的 tabelviewcontroller(我试图包括所有相关部分),但由于某种原因,当我运行应用程序时我有每个表格单元格(全部七个)中出现相同的数据标签。有人可以看到我看不到的错误吗...非常感谢

以下所有代码均来自tableviewcontroller.m 我让我的数组在 View 中加载

- (void)viewDidLoad
{
[super viewDidLoad];

// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;

self.contacts = [NSMutableArray arrayWithCapacity:10];
Contact *contact = [[Contact alloc] init];
contact.name = @"1";
[self.contacts addObject:contact];
contact.name = @"2";
[self.contacts addObject:contact];
contact.name = @"3";
[self.contacts addObject:contact];
contact.name = @"4";
[self.contacts addObject:contact];
contact.name = @"5";
[self.contacts addObject:contact];
contact.name = @"6";
[self.contacts addObject:contact];
contact.name = @"7";
[self.contacts addObject:contact];
}

我有 1 个部分

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}

我有数组中的行数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.contacts count];
}

我在这里创建我的细胞

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ContactTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ContactCell"];
Contact *contact = [self.contacts objectAtIndex:[indexPath row]];
cell.contactNameLabel.text = contact.name;
return cell;
}

所以我不确定为什么每个表格单元格标签都显示“7” 提前谢谢你

最佳答案

viewDidLoad

- (void)viewDidLoad {

     self.contacts = [NSMutableArray arrayWithCapacity:10];
     Contact *contact = [[Contact alloc] init];
     contact.name = @"1";
     [self.contacts addObject:contact];

     //Create new instance of Contact
     contact = [[Contact alloc] init];
     contact.name = @"2";
     [self.contacts addObject:contact];

     //Add objects same in way
}

如果没有创建新对象 [[Contact alloc] init],那么您正在更改同一个对象。

关于iOS TableView 在每个单元格中显示相同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23820833/

相关文章:

ios - Swift 服务器实现

ios - Swift 2.0 一个 View Controller 中的两个 TableView cellForRowIndexPath

objective-c - 使用@property(copy) 与@property(retain) 的经验法则是什么?

ios - UITableView 以编程方式在 UIScrollView 内部不调用委托(delegate)方法

objective-c - 根据子 NSMutableDictonary 的键值从 NSMutableArray 中检索对象

iphone - 如何在 UITextView 中检测用户输入的字符

ios - UIStackView 中 UILabels 上的动画隐藏属性会导致不同的动画

ios - Array/NSMutableArray 的最大限制是多少?我没有在日志中获取完整的 JSON 数据

ios - 如何将 2 个 NSDictionary Contain 数组合并到一个 NSMutableArray

ios - 填充 NSmutableDictionary 错误