将JSON数组转换为UIPickerView的数组

时间:2015-03-12 16:46:25

标签: ios nsarray

我需要从数组中的对象填充UIPickerView。

这是我用作选择器视图的数据源的数组的输出:

MESSAGEARRAY=
(
        {
        baggage = 4;
        id = 1;
        name = auto;
        passenger = 4;
        "resource_uri" = "/rest/type_vehicle/1/";
    },
        {
        baggage = 8;
        id = 2;
        name = miniban;
        passenger = 8;
        "resource_uri" = "/rest/type_vehicle/2/";
    },
        {
        baggage = 6;
        id = 3;
        name = camioneta;
        passenger = 6;
        "resource_uri" = "/rest/type_vehicle/3/";
    }
)

这是我用来做的方法:

// The number of columns of data
- (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 4;
}

// The number of rows of data
- (int)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return _pickerData.count;
}

// The data to return for the row and component (column) that's being passed in
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return _pickerData[component][row];
}

但该应用程序崩溃并显示以下错误消息:

[__NSDictionaryM objectAtIndexedSubscript:]: unrecognized selector sent to instance

我在这里做错了什么?

3 个答案:

答案 0 :(得分:0)

这是问题_pickerData[component][row]; _pickerData[component]会像这样返回NSDictionary

{
        baggage = 4;
        id = 1;
        name = auto;
        passenger = 4;
        "resource_uri" = "/rest/type_vehicle/1/";
}

您不能要求NSDictionary[row],因为它不是NSArray。这就是为什么你会收到这个错误。

答案 1 :(得分:0)

此错误可能意味着您正在使用NSArray作为NSDictionary,很可能您在这里获取字典而不是数组

请仔细调试并检查您是否正在处理预期的类型。

答案 2 :(得分:0)

我更改了错误的方法如下:

- (int)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [_pickerData [row] objectForKey:@"name"];
}

现在它工作正常。 谢谢。