Iphone PickerView只返回添加到数组中的最后一个对象
我正在解析JSON文件中的一些数据Iphone PickerView只返回添加到数组中的最后一个对象,iphone,ios,nsmutablearray,uipickerview,Iphone,Ios,Nsmutablearray,Uipickerview,我正在解析JSON文件中的一些数据 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"airports" ofType:@"json"]; NSString *jsonData = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL]; NSArray *airports = [NSJSON
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"]];
}
正在发生的事情是,您正在重复创建airportsArray。你摧毁了之前的一切
airportsArray = [[NSMutableArray alloc]init];
将这一行移到块中…的
之外。发生的事情是,您正在重复创建AirportsRay。你摧毁了之前的一切
airportsArray = [[NSMutableArray alloc]init];
将这一行移到<代码>块中…的之外。这是因为每次循环迭代时,您都在分配AirportsRay
因此,在循环外分配一次,如下所示:
airportsArray = [[NSMutableArray alloc]init];
for (NSDictionary *result in airports)
{
NSLog(@"%@ ", [result objectForKey:@"name"]);
[airportsArray addObject:[result objectForKey:@"name"]];
}
这是因为每次循环迭代时,您都在分配airportsArray
因此,在循环外分配一次,如下所示:
airportsArray = [[NSMutableArray alloc]init];
for (NSDictionary *result in airports)
{
NSLog(@"%@ ", [result objectForKey:@"name"]);
[airportsArray addObject:[result objectForKey:@"name"]];
}
非常感谢你!我根本没有注意到这一点非常感谢你!我根本没有注意到这一点+1谢谢。B每个人都已经注意到了我的“小”错误+1谢谢。B每个人都已经注意到了我的“小”错误您能否使用NSLog(@“%@”,airportsArray)检查airportsArray的内容;您能否使用NSLog(@“%@”,airportsArray)检查airportsArray的内容;