如何从 plist iOS 读取数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16269126/
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
How to read Array from plist iOS
提问by ram2013
I am trying to read plist which contains array
我正在尝试读取包含数组的 plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>key1</key>
<string>value1</string>
<key>key2</key>
<string>value2</string>
<key>keyarray1</key>
<array>
<string>keyitem1</string>
<string>keyitem2</string>
</array>
</dict>
</plist>
when i try to read valueForKey:@"keyarray1", I get null value. I tried to read as a string and array nut no use.
当我尝试读取 valueForKey:@"keyarray1" 时,我得到空值。我试图读取一个字符串和数组 nut 没有用。
My Code
我的代码
NSDictionary * values=[[NSDictionary alloc] initWithContentsOfFile:@"values.plist"];
NSArray *arrayValues=[[NSArray alloc] initWithArray:[values valueForKey:@"keyarray1"]];
回答by rptwsthi
First of all Check your plist looks like:
首先检查你的 plist 看起来像:
Now write following lines where you are accessing your plist
现在在您访问 plist 的地方写下以下几行
Objective-C:
目标-C:
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Values" ofType:@"plist"]];
NSArray *array = [dictionary objectForKey:@"keyarray1"];
NSLog(@"dictionary = %@ \narray = %@", dictionary, array);
Here is the complete screen shot (with log output) of my work window:
这是我的工作窗口的完整屏幕截图(带有日志输出):
Swift:
迅速:
let dictionary = NSDictionary(contentsOfFile: Bundle.main.pathForResource("Values", ofType: "plist")!);
let array = dictionary?["arrayKey"] as! NSArray
print("dictionary=", dictionary, "\narray =", array)
回答by Arnlee Vizcayno
I know this question is too old and I'll just like to add more information for those people encounter this recently.
我知道这个问题太老了,我只想为最近遇到这个问题的人添加更多信息。
In my case I created a plist as Array(plist default is Dictionary with key "Root").
在我的例子中,我创建了一个 plist 作为数组(plist 默认是带有键“Root”的字典)。
then the xml looks like this:
然后 xml 看起来像这样:
On my view controller I initialize directly the Array instead of initializing the Dictionary then get object for key "Root":
在我的视图控制器上,我直接初始化数组而不是初始化字典然后获取键“Root”的对象:
Note:I only wanted to add this info since I only see initializing the Dictionary then get object for keys. Hope it will help you guys.
注意:我只想添加此信息,因为我只看到初始化字典然后获取键的对象。希望它会帮助你们。
回答by zadr
Where is the plist stored? Is it in the app bundle? If so, you probably want to use [[NSBundle mainBundle] pathForResource:@"values" ofType:@"plist"]
to get the path, instead of hardcoding @"values.plist"
.
plist 存储在哪里?它在应用程序包中吗?如果是这样,您可能想使用[[NSBundle mainBundle] pathForResource:@"values" ofType:@"plist"]
获取路径,而不是硬编码@"values.plist"
。
After you have the path down correctly, you can then get the array from the dictionary without any problems, with something like [values objectForKey:@"keyarray"]
.
正确找到路径后,您就可以毫无问题地从字典中获取数组,例如 [values objectForKey:@"keyarray"]
.
Final note: there is a difference between objectForKey:
and valueForKey:
. You're currently using valueForkey:
which is part of NSKeyValueCoding
, a protocol that NSDictionary happens to conform to. You should use objectForKey:
(or syntactic sugar accessors, i.e. dictionary[@"key"]
) instead, as they are the proper ways of accessing a value from a dictionary.
最后说明:objectForKey:
和之间有区别valueForKey:
。您当前使用的valueForkey:
是NSKeyValueCoding
NSDictionary 恰好符合的协议的一部分。您应该改用objectForKey:
(或语法糖访问器,即dictionary[@"key"]
),因为它们是从字典中访问值的正确方法。
回答by Sunil Zalavadiya
Can you try following code?
你可以试试下面的代码吗?
NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"values" ofType:@"plist"];
NSDictionary * values=[[NSDictionary alloc] initWithContentsOfFile:plistPath];
NSArray *arrayValues=[[NSArray alloc] initWithArray:[values valueForKey:@"keyarray1"]];
NSLog(@"arrayValues = %@",arrayValues);
I got following output in log:-
我在日志中得到以下输出:-
arrayValues = (
keyitem1,
keyitem2
)
回答by Hyman
Swift 4
斯威夫特 4
As in Swift 4 you can use codable & PropertyListDecoder
与 Swift 4 一样,您可以使用codable 和 PropertyListDecoder
func setData() {
// location of plist file
if let settingsURL = Bundle.main.path(forResource: "JsonPlist", ofType: "plist") {
do {
var settings: MySettings?
let data = try Data(contentsOf: URL(fileURLWithPath: settingsURL))
let decoder = PropertyListDecoder()
settings = try decoder.decode(MySettings.self, from: data)
print("array is \(settings?.keyarray1 ?? [""])")//prints ["keyitem1", "keyitem2"]
} catch {
print(error)
}
}
}
}
struct MySettings: Codable {
var keyarray1: [String]?
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
keyarray1 = try values.decodeIfPresent([String].self, forKey: .keyarray1)
}
}
For more see this How to read from a plist with Swift 3 iOS app
有关更多信息,请参阅如何使用 Swift 3 iOS 应用程序读取 plist
回答by Ravindhiran
Try this
尝试这个
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"values.plist"];
NSMutableDictionary *dict =[NSMutableDictionary dictionaryWithContentsOfFile:finalPath];
NSArray *arr =[dict valueForKey:@"keyarray1"];
NSLog(@"%@",arr);