我正在解析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"]];
}
答案 0 :(得分:2)
这是因为您每次循环迭代都会分配AirportsArray 。
所以在循环外部分配一次:
airportsArray = [[NSMutableArray alloc]init];
for (NSDictionary *result in airports)
{
NSLog(@"%@ ", [result objectForKey:@"name"]);
[airportsArray addObject:[result objectForKey:@"name"]];
}
答案 1 :(得分:1)
如果您反复创建机场阵列,会发生什么。在此之前你会破坏它所处的位置。
airportsArray = [[NSMutableArray alloc]init];
将此行移至for...in
区块之外。