如何从属性列表中获取特定数据?

时间:2015-10-27 11:47:33

标签: ios objective-c

我试图从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创建之间的区别吗?

2 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分:0)

如果您的plist文件包含数组,例如fruits数组,则可以使用+[NSArray arrayWithContentsOfFile:]。但如果它包含字典(这里就是这种情况),则必须使用+[NSDictionary dictionaryWithContentsOfFile:]

如果您事先并不知道数据类型,请查看适用于这两种情况的NSPropertyListSerialization课程。