从plist数组中检索数据

时间:2013-02-16 21:04:17

标签: objective-c cocoa plist nsdata

我很难解决这个问题。

我正在创建一个测验。在plist中有问题......和可能的答案,这是我的plist

<plist version="1.0">
<dict>
<key>quest</key>
<array/>
<key>Quest1</key>
<string>3234</string>
<key>A</key>
<string>3</string>
<key>B</key>
<string>2</string>
<key>C</key>
<string>1</string>
</dict>
</plist>

该数组被称为quest,我希望能够从代码和3个答案中提取“Quest1”....这是我的代码,但我似乎错过了一些东西来得到它显示

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [path objectAtIndex:0];
NSString *plistpath = [documentsPath stringByAppendingPathComponent:@"question.plist"];
if(![[NSFileManager defaultManager] fileExistsAtPath:plistpath])
{
    plistpath = [[NSBundle mainBundle] pathForResource:@"question" ofType:@"plist"];
}
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistpath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization     propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
{
NSLog(@"error reading plist: %@, format:%d",errorDesc, format);

}
  self.question.text = [temp objectForKey:@"quest"];
  self.answer1.text =[temp objectForKey:@"A"];
  self.answer2.text =[temp objectForKey:@"B"];
  self.answer3.text =[temp objectForKey:@"C"];

1 个答案:

答案 0 :(得分:0)

尝试下面的代码。它会帮助你

NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [path objectAtIndex:0];
NSString *plistpath = [documentsPath stringByAppendingPathComponent:@"question.plist"];
NSMutableArray *savedStock = [[NSMutableArray alloc] initWithContentsOfFile:plistFilePath];
 for (int i=0; i<[savedStock count]; i++)
    {
        [A-array addObject:[[savedStock objectAtIndex:i] valueForKey:@"A"]];
        [B-array addObject:[[savedStock objectAtIndex:i] valueForKey:@"B"]];
    }