想从iPhone中的plist中获取字典数组中的数据?

时间:2014-02-21 09:39:02

标签: ios iphone plist

我是iPhone新手,根据要求我必须从tableview中的问题列表中选择一个问题,并希望在下一个新视图中显示该问题。所以我将行值发送到新的Xib文件中创作的时间。

我将我的问题-iss作为一个字典格式数组存储在plist中。我可以从Plist中获取数组,但是无法获取字典数据..我使我的自定义类存储问题-Release.but at new get只有存储在plist中的最后一个问题。 请帮帮我。谢谢你..

此处我附加了我的代码tableView.m,newView.mcustomClass.m ..

tableView.m

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {

            NSLog(@" index row value:%d",indexPath.row);
           NSInteger row=indexPath.row;
            questionViewController *viewController1 =
            [[questionViewController alloc] initWithNibName:@"questionViewController" bundle:[NSBundle mainBundle]];
            viewController1.rowValue=row;
                self.viewController = viewController1;
            [self.viewController.navigationItem setTitle:@"Ques Details"];


        [self.navigationController pushViewController:self.viewController animated:YES];
    }

在新的Xib文件中,在ViewDidLoadFunction

newView.m

    - (void)viewDidLoad
    {
      //rowValue tells me which row is selected
        [self firstView:rowValue];

    }
    -(void)firstView: (NSInteger)indexNumber{
        NSString *thePath = [[NSBundle mainBundle]  pathForResource:@"Qus_ans" ofType:@"plist"];
        NSArray *rawElementsArray = [[NSArray alloc] initWithContentsOfFile:thePath];
        NSDictionary *eachElement;
     //overlap the data here   
     for (eachElement in rawElementsArray)
        {
           element = [[Question alloc] initWithDictionary:eachElement];}
   //get only last question in the plist
   questionLabel.text =[NSString stringWithFormat:@"%@",element.ques];

     }
    element is my Custom class object.This is my custom class:
    Question.m

    - (id)initWithDictionary:(NSDictionary *)aDictionary {

        self = [[Question alloc] init];
        if (self) {

            self.ques = [aDictionary valueForKey:@"question"];
            self.ans = [aDictionary valueForKey:@"answer"];

            [self data];
        }
        return self;
    }

    Here element.ques is overlapped with the last value.
    How I get proper question without using the forLoop...

这是我的plist格式

<array>
    <dict>
        <key>question</key>
        <string>Approximately how much does the human brain weigh?</string>
        <key>answer</key>
        <string>Three pounds</string>
    </dict>
    <dict>
        <key>question</key>
        <string>The brain has this number of The brain has this number of nerve cells?</string>
        <key>answer</key>
        <string>1 to 100 billion</string>
    </dict>

1 个答案:

答案 0 :(得分:0)

好吧,我不完全确定我理解你的问题,但是如果你想摆脱你的for循环(我猜是这样),你可以简单地写一下

NSArray *rawElementsArray = [[NSArray alloc] initWithContentsOfFile:thePath];
NSDictionary * dic = rawElementsArray objectAtIndex:rowNumber];