我有一个 NSMutableArray *rows;
,我在 viewDidLoad
中初始化并填充数据。到那时,显然它已经有了数据。在本例中,为三个条目。
然后在 tableView:cellForRowAtIndexPath
中,我调用 [rows objectAtIndex:indexPath.row]
。但是,此时 rows
数组仍包含三个条目,但这些条目的值为 0x00000000
而不是原始值(例如“id”为 12345
但现在是 0x00000000
。
在我看来,rows
中的数据值在 viewDidLoad
和 tableView: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/