我正在解析 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"]];
}