0

我有一个属性列表文件“someFile.plist”,在 plist 中有两行“row1”和“row2”,每行都有一个字符串值,即“Y”或“N”——如果我想检查“someFile” “row2”的.plist”文件以获取该行的值并将其读入目标c中的字符串,我该怎么做?我正在使用 Xcode 为 iphone App 编写代码。

4

3 回答 3

9

加载.plistNSDictionarylike中:

NSString *path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];

循环NSDictionary使用类似的东西:

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}
于 2012-09-03T15:44:36.733 回答
2

如果您想将“row2”的值获取到 String,那么这取决于您是具有 Dictionary 类型还是 Array 类型。在字典类型的情况下:

NSString *path = [[NSBundle mainBundle] pathForResource:@"pListFileName" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSString valueOfRow2 = [dict objectForKey:@"row2"]);
NSLog(@"The value of row2 is %@", valueOfRow2);

在数组的情况下:

NSString *path = [[NSBundle mainBundle] pathForResource:@"pListFileName" ofType:@"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile: path];
//the indexes of NSArray is counted from 0, not from 1
NSString valueOfRow2 = [array objectAtIndex:1];
NSLog(@"The value of row2 is %@", valueOfRow2);

您可以分别使用 NSMutableDictionary 和 NSMutableArray。修改它们会更容易。

于 2015-03-07T02:42:09.903 回答
0

对于 Swift 3.0:

if let path = Bundle.main.path(forResource: "YourPlistFile", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
            let value = dict["KeyInYourPlistFile"] as! String
    }
于 2017-10-30T06:05:53.497 回答