2012-01-05 123 views
0

为什么naam输出(NULL)? (抱歉,在知道这是基本的东西,但我新用的Plist)读出Plist问题

这是plist中: enter image description here

这里的方法:

- (id) init { 

self = [super init]; 
if (self) { 
    NSString *errorDesc = nil; 
    NSPropertyListFormat format; 
    NSString *plistPath; 
    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                   NSUserDomainMask, YES) objectAtIndex:0]; 
    plistPath = [rootPath stringByAppendingPathComponent:@"Data.plist"]; 
    NSLog(@"path: %@",plistPath); 
    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) { 
     plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]; 
    } 
    NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath]; 

    NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization 
              propertyListFromData:plistXML 
              mutabilityOption:NSPropertyListMutableContainersAndLeaves 
              format:&format 
              errorDescription:&errorDesc]; 
     NSLog(@"temp: %@",temp); 
    if (!temp) { 
     NSLog(@"Error reading plist: %@, format: %d", errorDesc, format); 
    } 
    self.personName = [temp objectForKey:@"Name"]; 
    NSLog(@"NAAM:%@",[temp objectForKey:@"Name"]); 
    self.phoneNumbers = [NSMutableArray arrayWithArray:[temp objectForKey:@"Phones"]]; 


} 
return self;} 

the output

回答

1

因为温度是一个只包含一个键的字典:@“Root”。您正在寻找在内部字典的对象:[[temp objectForKey:@"Root"] objectForKey:@"Name"]

+0

谢谢;这样可行。我怎样才能(只)读取电话中的第1项? – Foo 2012-01-05 19:25:53

1

尝试

NSLog(@"NAAM: %@", [temp valueForKeyPath:@"Root.Name"]); 

踩着第一个电话来自Phones做到这一点:

NSDictionary *root = [temp valueForKey:@"Root"]; 
[[root valueForKey:@"Phones"] objectAtIndex:0]; 
+0

谢谢!我如何(仅)在提取ROOT后阅读Phones中的Item 1? – Foo 2012-01-06 12:18:45

1

先尝试提取ROOT。

NSDictionary* root=[temp objectForKey:@"Root"]; 
NSLog(@"NAAM:%@",[root objectForKey:@"Name"]); 
+0

谢谢!我如何(仅)在提取ROOT后阅读Phones中的Item 1? – Foo 2012-01-05 15:15:45

+0

就像这样:'NSArray * phones = [root objectForKey:@“Phones”]; NSString * phone1 = [phones objectAtIndex:0];' – 2012-01-07 13:16:16

0

我 “Words.plist”

<dict> 
    <key>Root</key> 
    <array> 
     <string>sunday</string> 
     <string>monday</string> 
     <integer>44</integer> 
    </array> 
</dict> 


NSString *StringsFromPList = [[NSBundle mainBundle] bundlePath]; 
NSString *itemPositionPlistLocation = [StringsFromPList stringByAppendingPathComponent:@"Words.plist"]; 
_myDictionary= [[NSDictionary alloc] initWithContentsOfFile:itemPositionPlistLocation]; 
NSArray * items = [_myDictionary objectForKey:@"Root"]; 
NSLog(@"%@", items); 

希望它可以帮助一点:)