来自NSDictionary的UIPickerView数据

时间:2013-04-24 07:30:58

标签: ios objective-c xcode nsdictionary uipickerview

我有这样的网络服务日期:

{
            "idlife_stage_question" = 43;//..basically this should be key
            "life_stage_idlife_stage" = 1;
            "profile_idprofile" = 0;
            "question_text" = "example";//..this should be object
            sequence = 42;
    }

现在我需要来自每个JSON字典的“idlife_stage_question”和“question_text”,并在UIPickerView中加载“question_text”,然后在UILabel中显示所选的行文本。此外,我需要为相应的“question_text”获取“idlife_stage_question”,以便稍后我可以向服务器发送“idlife_stage_question”。我怎么能用NSDictionary做到这一点?

修改

我的要求是:

  1. 从JSON获取“idlife_stage_question”和“question_text”。
  2. 在NSMutableDictionary中设置“idlife_stage_question”和“question_text”
  3. 使用“question_text”填充UIPicker
  4. 在标签中显示选定的行文字
  5. 从“question_text”对应的NSMutableDictionary获取“idlife_stage_question”,将其发送到服务器。

2 个答案:

答案 0 :(得分:1)

假设您拥有self.questionsArray来自webservice的所有数据且UIPickerView中只有一个组件

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

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [self.questionsArray count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
   return self.questionsArray[row][@"question_text"];
}

解除pickerView

的方法
- (void)dismissPickerView
{
    //Get the selected Row in picker
    NSInteger selectedQuestionIndex = [self.pickerView selectedRowInComponent:0];
    NSDictionary *question = self.questionsArray[selectedQuestionIndex];

    self.label.text = question[@"question_text"];

    //Use this value to send back to server
    NSInteger questionId = [question[@"idlife_stage_question"] integerValue];

}

答案 1 :(得分:0)

将json解析为nsdictionary

-(void) requestFinished : (ASIHTTPRequest *) request {
        NSArray *myArray = [NSJSONSerialization 
                                              JSONObjectWithData:[request responseData]
                                              options:kNilOptions 
                                              error:&error];
        }

检查数组层次结构:

NSLog(@"%@", myArray);

现在可以将数组的每个元素提取到NSDictionary中。迭代数组时,每个对象都是NSDictionary。

迭代你的数组

NSEnumerator *myIterator = [myArray objectEnumerator];
    id anObject;

    while( anObject = [myIterator nextObject]){
        NSLog(@"%@", [anObject objectForKey@"question_text"]);
        // get each value of your question_text in a new NSArray and use that array for UIPickerView demostrated in the following link
    }

然后看here如何以编程方式创建UIPickerView