ios - 为什么 UITableView 的 NSMutableArray 数据在被 tableView 使用时丢失 :cellForRowAtIndexPath?

标签 ios objective-c automatic-ref-counting

我有一个 NSMutableArray *rows;,我在 viewDidLoad 中初始化并填充数据。到那时,显然它已经有了数据。在本例中,为三个条目。

然后在 tableView:cellForRowAtIndexPath 中,我调用 [rows objectAtIndex:indexPath.row]。但是,此时 rows 数组仍包含三个条目,但这些条目的值为 0x00000000 而不是原始值(例如“id”为 12345 但现在是 0x00000000

在我看来,rows 中的数据值在 viewDidLoadtableView:cellForRowAtIndexPath 之间的某处被清空。可能是什么原因造成的?

编辑

这是代码:

ViewController.m:

@implementation ViewController

NSMutableArray *rows;

- (void)viewDidLoad
{
    rows = [[NSMutableArray alloc] init];
    [rows setArray:myData]; // myData is als an NSMutableArray populated from JSON data.
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    User *user = [rows objectAtIndex:indexPath.row]; // At this point 'rows' contains three entries but the values are empty.
}

@end

编辑2

以下是经过几次建议更改后的代码:

ViewController.m

@interface ViewController()
{
    NSMutableArray *rows;
}

@implementation ViewController
- (void)setRowsFromJSON
{
    NSString *fileContents = [NSString stringWithContentsOfFile:@"data.json" encoding:NSUTF8StringEncoding error:nil];
    NSData *jsonData = [fileContents dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];

    rows = [NSMutableArray arrayWithCapacity:[jsonArray count]];
    User *user;

    for (NSDictionary *aUser in jsonArray) {
        user = [[User alloc] init];
        user.id = [aUser valueForKey:@"id"];
        user.name = [aUser valueForKey:@"name"];
        [rows addObject:user];
    }
}

- (void)viewDidLoad
{
    [self setRowsFromJSON];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    User *user = [rows objectAtIndex:indexPath.row]; // At this point 'rows' contains three entries but the values are empty.
}

@end

最佳答案

0x000000000 为零。这意味着该行没有指向任何地方。

我在 iOS 5.1 上运行应用程序时遇到了同样的问题。问题是您假设 viewDidLoad 始终在 tableview:cellForRowAtIndexPath: 之前调用。但事实并非一定如此。第一个是 View Controller 的方法。第二个是Table View Data Source 的方法。两者是同一个对象这一事实纯属偶然。

就我而言, TableView Controller 方法在 viewDidLoad 之前调用,然后在 viewDidLoad 之后再次调用,因为对 View 表属性的某些修改总是会重新加载。

尝试初始化,例如 - numberOfSectionsInTableView:

关于ios - 为什么 UITableView 的 NSMutableArray 数据在被 tableView 使用时丢失 :cellForRowAtIndexPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16242341/

相关文章:

ios - 无法将我的 objective-c 类的基类设置为 swift 类

iphone - Facebook SDK : FBLoginView for publish stream

objective-c - 我是否需要释放 Objective-C 代码中的 C 变量(带有 ARC 的 iOS 6)?

ios - 故意使存档失败的代码

TableViewCells 中的 iOS Facebook SDK 配置文件图片

ios - 是否可以在拆分模式下为屏幕的全宽在键盘上方创建 inputAccessoryView?

objective-c - 使用 XCode 将非 ARC 项目转换为 Objective-C ARC 时,Clang 失败,退出代码为 254

ios - 如何用双指针声明NSString变量

ios - 核心数据 : Parent Entity Vs Relationships

objective-c - IOS:使用标签值更改 UIImageView