如何使用 Xcode 将属性列表文件键的值读入 iphone 应用程序的字符串中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12250739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 01:24:29  来源:igfitidea点击:

How do I read a value of a property list file key into a string for iphone app using Xcode

objective-ciphonexcodeplist

提问by MeisterPlans

I have a property list file "someFile.plist" and within the plist I have two rows "row1" and "row2" each with a string value that is either "Y" or "N" - If I want to check the "someFile.plist" file for "row2" to obtain the value of that row and read it into a string in objective c, how would I do that? I am coding for an iphone App using Xcode.

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

回答by Anne

Load the .plistinto a NSDictionarylike:

加载.plist到一个NSDictionary像:

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

Loop through the NSDictionaryusing something like:

循环NSDictionary使用类似的东西:

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

回答by Darius Miliauskas

If you want to get the value of "row2" to String then it depends if you are having Dictionary type or Array type. In the case of Dictionary type:

如果您想将“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);

and in the case of Array:

在数组的情况下:

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);

You can use NSMutableDictionary and NSMutableArray respectively. It would be more easy to modify them.

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

回答by FARAZ

For Swift 3.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
    }