0

NSMutableArray *rows;データを初期化して入力する がありますviewDidLoad。その時点で、明らかにデータがあります。この場合、3 つのエントリ。

それからtableView:cellForRowAtIndexPath私は呼んで[rows objectAtIndex:indexPath.row]います。ただし、この時点では、rows配列にはまだ 3 つのエントリが含まれていますが、これらのエントリの値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
4

1 に答える 1

1

0x000000000 はゼロです。つまり、その行はどこも指していません。

iOS 5.1 でアプリを実行すると、同じ問題が発生しました。問題は、viewDidLoad が常に tableview:cellForRowAtIndexPath: の前に呼び出されると想定していることです。しかし、そうである必要はありません。1つ目はView Controllerのメソッドです。2 つ目は、Table View Data Source のメソッドです。両方が同じオブジェクトであるという事実は偶然です。

私の場合、viewDidLoad の前に呼び出され、viewDidLoad の後に再度呼び出された Table View Controller メソッドは、View Table のプロパティの一部の変更が常にリロードされるためです。

たとえば、次のように初期化してみてください – numberOfSectionsInTableView:

于 2013-04-26T18:38:31.730 に答える