繁体   English   中英

从plist读取字典和子字典

[英]Reading dictionary and child dictionary from plist

我创建了一个plist文件,如下所示:

在此处输入图片说明
由此可以将所有plist信息提取到NSArray中:

-(NSArray *)Topics
{
    if(!_Topics)
    {
        _Topics = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"TopicData" ofType:@"plist"]];
    }
    return _Topics;
}

并使用此数组加载TopicTitle的表视图:

cell.textLabel.text = [[self.Topics objectAtIndex:indexPath.row] valueForKey:@"TopicTitle"];

当选择表中的一行时,我将名为“ Questions”的字典传递给下一个ViewController,如下所示:

NSDictionary *questions = [[self.Topics objectAtIndex:indexPath.row] valueForKey:@"Questions"];
[self.detailViewController setQuestions:(questions)];

在这里,我想遍历每个“问题”字典,并通过执行以下操作将“ QuestionText”和“ AnswerOne / Two ...”字符串加载到对象数组中:

TopicQuestions = [NSMutableArray array];
for(NSDictionary *ques in self.Questions)
{
    Question* q = [[Question alloc] init];
    q.Question = (NSString*)[ques objectForKey:@"QuestionText"];
    q.AnswerOne = (NSString*)[ques objectForKey:@"QuestionText"];
    q.AnswerTwo = (NSString*)[ques objectForKey:@"QuestionText"];
    q.AnswerThree = (NSString*)[ques objectForKey:@"QuestionText"];
    q.AnswerFour = (NSString*)[ques objectForKey:@"QuestionText"];
    [TopicQuestions addObject:q];
}

但是“问题”字典似乎没有可用的数据,它知道有4个子对象,但没有这些对象的所有键-对值:

在此处输入图片说明

所以我的问题是我应该如何将“问题”字典传递给下一个ViewController,以便仍然能够访问“ QuestionText”和“ AnswerOne / Two ...”节点?

还是有一种更好的方式来读取字符串而不循环遍历每个“问题”字典?

我认为您没有正确地获得问题字典。 在屏幕快照中, ques对象是NSString对象,而不是NSDictionary。 因此让objectForKeyNSString对象ques是行不通的(真的应该崩溃的应用程序)。

试试这个循环:

for(NSString *ques in self.Questions)
{
    NSDictionary *dict = [self.questions objectForKey:ques];
    Question* q = [[Question alloc] init];
    q.Question = (NSString*)[dict objectForKey:@"QuestionText"];
    q.AnswerOne = (NSString*)[dict objectForKey:@"QuestionText"];
    q.AnswerTwo = (NSString*)[dict objectForKey:@"QuestionText"];
    q.AnswerThree = (NSString*)[dict objectForKey:@"QuestionText"];
    q.AnswerFour = (NSString*)[dict objectForKey:@"QuestionText"];
    [TopicQuestions addObject:q];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM