gpt4 book ai didi

iphone - PickerView 仅返回我的数组中添加的最后一个对象

转载 作者:行者123 更新时间:2023-11-28 20:13:41 25 4
gpt4 key购买 nike

我正在从一个 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"]];


}

最佳答案

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

所以在循环外分配一次:

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

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

关于iphone - PickerView 仅返回我的数组中添加的最后一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19024253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com