2015-10-27 70 views
-2

我想從plist文件中獲取特定數據而不創建新對象。如何從屬性列表中獲取特定數據?

NSArray *fruits = @[@"Apple", @"Mango", @"Pineapple", @"Plum", @"Apricot"]; 

NSString *filePathFruits = [documents stringByAppendingPathComponent:@"fruits.plist"]; 
[fruits writeToFile:filePathFruits atomically:YES]; 

NSDictionary *miscDictionary = @{@"anArray" : fruits, @"aNumber" : @12345, @"aBoolean" : @YES}; 

NSString *filePathDictionary = [documents stringByAppendingPathComponent:@"misc-dictionary.plist"]; 
[miscDictionary writeToFile:filePathDictionary atomically:YES]; 

NSArray *loadedFruits = [NSArray arrayWithContentsOfFile:filePathFruits]; 
NSLog(@"Fruits Array > %@", loadedFruits); 

NSString *string1 = [[NSArray arrayWithContentsOfFile:filePathDictionary] objectAtIndex:1]; 
NSString *string2 = [loadedFruits objectAtIndex:1]; 

NSLog(@"Without New array object: %@",string1); // output is : null 
NSLog(@"With array object : %@",string2); // output is : mango 

你能解釋一下string1和string2的區別嗎?

+0

可能的重複[如何使用Xcode爲iphone應用程序讀取屬性列表文件密鑰的值爲字符串](http://stackoverflow.com/questions/12250739/how-do-i-read-a - 值對的一屬性列表文件鍵 - 到 - 一個字符串換iphone-APP-U) –

回答

0

非常容易 See This Answer

@interface ViewController() 

@property (nonatomic, strong) NSDictionary* pDictionary; 

@end 

@implementation ViewController 

// other code here 

// within readDefinitionsFile method 
self.pDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath]; 

使用pDictionary檢索您感興趣的定義。

NSString* plistData = [self.pDictionary objectForKey:@"aKeyYouWillRetrieveFromSomewhere"]; 
if(definition) { 
    NSLog(@"definition is %@ for key %@", plistData, @"aKeyYouWillRetrieveFromSomewhere"); 
} else { 
    NSLog(@"no data for key %@", @"aKeyYouWillRetrieveFromSomewhere"); 
} 
0

如果您的plist文件包含一個數組,像你fruits陣列,可以使用+[NSArray arrayWithContentsOfFile:]。但如果它包含字典(這裏是這種情況),則必須使用+[NSDictionary dictionaryWithContentsOfFile:]

如果您事先不知道數據類型,請查看NSPropertyListSerialization類,它將與這兩個類一起使用。