0

我正在解析 JSON 文件中的一些数据

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"airports" ofType:@"json"];

NSString *jsonData = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

NSArray *airports = [NSJSONSerialization JSONObjectWithData:[jsonData dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];


for (NSDictionary *result in airports)
{

    NSLog(@"%@ ", [result objectForKey:@"name"]);
    airportsArray = [[NSMutableArray alloc]init];
    [airportsArray addObject:[result objectForKey:@"name"]];


}

NSLOG 正确显示了所有机场,但是当 pickerView 仅显示我文件中的最后一个机场时。

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1
;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:    (NSInteger)component
 {
return [airportsArray count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row  forComponent:    (NSInteger)component
{
return [airportsArray objectAtIndex:row];
}

更新:感谢您的回复。我修复了我的代码。我只是在 For in 循环中分配数组。

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"airports" ofType:@"json"];

NSString *jsonData = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

NSArray *airports = [NSJSONSerialization JSONObjectWithData:[jsonData dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

    airportsArray = [[NSMutableArray alloc]init];


for (NSDictionary *result in airports)
{

    NSLog(@"%@ ", [result objectForKey:@"name"]);
    [airportsArray addObject:[result objectForKey:@"name"]];


}
4

2 回答 2

2

这是因为您在每次循环迭代时分配 airportsArray

因此,在循环外将其分配一次:

airportsArray = [[NSMutableArray alloc]init];
for (NSDictionary *result in airports)
{

    NSLog(@"%@ ", [result objectForKey:@"name"]);
    [airportsArray addObject:[result objectForKey:@"name"]];
}
于 2013-09-26T09:27:06.963 回答
1

发生的事情是您重复创建 airportsArray。而你摧毁了在此之前的位置。

airportsArray = [[NSMutableArray alloc]init];

将这条线移到您的for...in街区之外。

于 2013-09-26T09:25:21.803 回答