ios - UIPickerView 为空,数据源为 JSON 数组

标签 ios json uipickerview

我正在尝试使用解析为 NSArray 的 JSON 数据填充 UIPickerView。

控制台显示 JSON 正在正确解析,但 UIPickerView 仍为空。

这是我的代码:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView 
{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    //set number of rows
    return self.terrainJsonArray.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    //set item per row
    return [self.terrainJsonArray objectAtIndex:row];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Parse JSON 

    NSString *terrainString = [NSString stringWithFormat:@"http://terrainracing.com/ios/events_json.php"];

    NSURL *terrainUrl = [NSURL URLWithString:terrainString];

    NSData  *terrainData = [NSData  dataWithContentsOfURL:terrainUrl];

    NSError *error;

    NSArray *terrainJsonArray = [NSJSONSerialization JSONObjectWithData:terrainData options:kNilOptions error:&error];

    NSLog(@"%@", terrainJsonArray);
}

最佳答案

选择器 View 委托(delegate)方法正在查看类instance变量self.terrainJsonArray(实际上它是实例变量的属性 getter ) .

viewDidLoad 中,您声明并记录一个名为 terrainJsonArray本地变量。该局部变量与实例变量没有任何联系。

您一定在 viewDidLoad 中收到编译器警告,例如“'terrainJsonArray' 的本地声明隐藏实例变量”。

更改此行:

NSArray *terrainJsonArray = [NSJSONSerialization JSONObjectWithData:terrainData options:kNilOptions error:&error];

至:

self.terrainJsonArray = [NSJSONSerialization JSONObjectWithData:terrainData options:kNilOptions error:&error];

关于ios - UIPickerView 为空,数据源为 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9831852/

相关文章:

ios - 南非市场的 Apple Pay

iPhone UITextField inputView 错误 : Assignement to readonly property

ios - iOS 8 的 ActionSheetPicker 替代品

ios - 在 swift 中将 JSON 字符串数组转换为 NSArray

php - JSON.parse 错误 #1132 : Invalid JSON parse input (Flex/Actionscript/PHP)

ios - UIPickerView 无法显示 JSON 数组数据

html - 在 Safari iPhone 的新标签页中打开链接

ios - 即使启用了后台模式和推送通知,Firebase 电话身份验证也会在 iOS 上弹出一个 reCAPTCHA 验证窗口

ios - updatedTransactions(transactionState == .restored) 与 paymentQueueRestoreCompletedTransactionsFinished

python - 无法将字符串转换为 pandas 中的 float (ValueError)