2015-10-27 77 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类,它将与这两个类一起使用。