我有一个NSMutableArray *rows;
我初始化并用viewDidLoad
. 在这一点上,显然,它有数据。在这种情况下,三个条目。
然后在里面tableView:cellForRowAtIndexPath
我打电话[rows objectAtIndex:indexPath.row]
。但是,此时rows
数组仍然包含三个条目,但这些条目的值0x00000000
不是原始值(例如,'id' was 12345
but is now 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
这是经过几次建议更改后的代码:
视图控制器.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