2012-01-05 72 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); 

希望它可以幫助一點:)