【问题标题】:How to get particular data from the property list?如何从属性列表中获取特定数据?
【发布时间】:2015-10-27 11:47:32
【问题描述】:

我正在尝试从 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 创建的区别吗?

【问题讨论】:

标签: ios objective-c


【解决方案1】:

非常简单 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");
}

【讨论】:

    【解决方案2】:

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

    如果您事先不知道数据类型,请查看适用于两者的 NSPropertyListSerialization 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多