ios 如何将 .plist 文件中的数据结构读入 NSArray
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/749504/
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 data structure from .plist file into NSArray
提问by Xetius
I was creating a data structure manually using the following:
我正在使用以下方法手动创建数据结构:
NSDictionary* league1 = [[NSDictionary alloc] initWithObjectsAndKeys: @"Barclays Premier League", @"name",
@"Premier League", @"shortname",
@"101", @"id", nil];
NSDictionary* league2 = [[NSDictionary alloc] initWithObjectsAndKeys: @"Coca-Cola Championship", @"name",
@"Championship", @"shortname",
@"102", @"id", nil];
NSDictionary* league3 = [[NSDictionary alloc] initWithObjectsAndKeys: @"Scottish Premier League", @"name",
@"SPL", @"shortname",
@"201", @"id", nil];
NSDictionary* league4 = [[NSDictionary alloc] initWithObjectsAndKeys: @"Champions League", @"name",
@"UCL", @"shortname",
@"501", @"id", nil];
contentArray = [[NSArray alloc] initWithObjects:
[[NSDictionary alloc] initWithObjectsAndKeys: @"English", @"category", [[NSArray alloc] initWithObjects: league1, league2, nil], @"leagues", nil],
[[NSDictionary alloc] initWithObjectsAndKeys: @"Scottish", @"category", [[NSArray alloc] initWithObjects: league3, nil], @"leagues", nil],
[[NSDictionary alloc] initWithObjectsAndKeys: @"Tournaments", @"category", [[NSArray alloc] initWithObjects: league4, nil], @"leagues", nil],
nil];
[league1 release];
[league2 release];
[league3 release];
[league4 release];
However, I thought this would be better if it was read from a file. So I created the file leagues.plist which has the following structure:
但是,我认为如果从文件中读取它会更好。所以我创建了具有以下结构的文件 Leagues.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">
<array>
<dict>
<key>category</key>
<string>English</string>
<key>leagues</key>
<array>
<dict>
<key>name</key>
<string>Barclays Premier League</string>
<key>shortname</key>
<string>Premier League</string>
<key>id</key>
<string>101</string>
</dict>
<dict>
<key>name</key>
<string>Coca-Cola Championship</string>
<key>shortname</key>
<string>Championship</string>
<key>id</key>
<string>102</string>
</dict>
</array>
</dict>
<dict>
<key>category</key>
<string>Scottish</string>
<key>leagues</key>
<array>
<dict>
<key>name</key>
<string>Scottish Premier League</string>
<key>shortname</key>
<string>SPL</string>
<key>id</key>
<string>201</string>
</dict>
</array>
</dict>
<dict>
<key>category</key>
<string>Tournaments</string>
<key>leagues</key>
<array>
<dict>
<key>name</key>
<string>Champions League</string>
<key>shortname</key>
<string>UCL</string>
<key>id</key>
<string>501</string>
</dict>
</array>
</dict>
</array>
</plist>
How do I read this file in. I have tried various methods but nothing has worked. I don't even know if I am looking in the right place for the file. For reference I am trying the following methods:
我如何读入这个文件。我尝试了各种方法,但没有任何效果。我什至不知道我是否在正确的地方寻找文件。作为参考,我正在尝试以下方法:
NSString* errorDesc = nil;
NSPropertyListFormat format;
NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"league" ofType:@"plist"];
NSData* plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
contentArray = (NSArray*)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
if (!contentArray) {
NSLog(errorDesc);
[errorDesc release];
}
or
或者
NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"league" ofType:@"plist"];
contentArray = [NSArray arrayWithContentsOfFile:plistPath];
or
或者
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *fooPath = [documentsPath stringByAppendingPathComponent:@"leagues.plist"];
NSLog(fooPath);
contentArray = [NSArray arrayWithContentsOfFile:fooPath];
NSLog(@"%@",contentArray);
This is finally driving me completely insane. Help please!
这终于让我完全疯了。请帮忙!
Thank you kindly
非常感谢你
回答by Kendall Helmstetter Gelner
NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"league" ofType:@"plist"];
contentDict = [NSDictionary dictionaryWithContentsOfFile:plistPath];
That answer is correct - are you sure that your file is in the app? Did you add it to your project, and check to see if it gets copied into your app bundle? If not, it might be the file was not added to the target you are building, an easy mistake to make especially if you have multiple targets.
该答案是正确的 - 您确定您的文件在应用程序中吗?您是否将它添加到您的项目中,并检查它是否被复制到您的应用程序包中?如果不是,则可能是该文件未添加到您正在构建的目标中,这是一个容易犯的错误,尤其是当您有多个目标时。
回答by Narayanan
Use this code if the plist
is in the resources folder of the project.
如果plist
位于项目的资源文件夹中,请使用此代码。
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"league" ofType:@"plist"];
contentArray = [NSArray arrayWithContentsOfFile:sourcePath];
If the plist
is inside the document directory of the app use this:
如果 位于plist
应用程序的文档目录中,请使用以下命令:
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *plistName = @"league";
NSString *finalPath = [basePath stringByAppendingPathComponent:
[NSString stringWithFormat: @"%@.plist", plistName]];
contentArray = [NSArray arrayWithContentsOfFile:finalPath];
回答by noRema
I had this issue but it wasn't working because I was putting the results from the pList into an array where it should have been a dictionary, i.e
我有这个问题,但它没有工作,因为我将 pList 的结果放入一个数组中,它应该是一个字典,即
NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"VehicleDetailItems" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
回答by bentford
Kendall is correct.
肯德尔是对的。
In my experience, you need to add your file to the "Resources" folder in xcode.
根据我的经验,您需要将文件添加到 xcode 中的“Resources”文件夹中。
回答by Xetius
For completeness, Kendall and bentford are completely correct. However, in my sample, contentArray was a property and by the end of the method it was going out of scope because arrayWithContentsOfFilecreates an auto-released object.
为了完整性,肯德尔和本特福德是完全正确的。但是,在我的示例中, contentArray 是一个属性,在方法结束时它超出了范围,因为arrayWithContentsOfFile创建了一个自动发布的对象。
To make this work correctly I needed to do 3 things:
为了使这项工作正常进行,我需要做 3 件事:
put the file in the resources folder
name the file correctly (was leagues.plist instead of league.plist)
read the file using [[NSArray alloc] initWithContentsOfFile:plistPath)];
将文件放在资源文件夹中
正确命名文件(是 Leagues.plist 而不是 League.plist)
使用[[NSArray alloc] initWithContentsOfFile:plistPath)]读取文件;
the third part creates an allocated NSArray that does not release when you exit the scope of this function... of course, this needed to be released in the dealloc function.
第三部分创建了一个分配的 NSArray,当你退出这个函数的作用域时它不会释放......当然,这需要在 dealloc 函数中释放。
回答by Xetius
Just to add. I had the same problem and the suggested solution helped me solve the problem, however I am not sure if I actually used the exact solution. In my case the problem was that the .plist file was added to a different target (had added a new target a moment before). Therefore the solution was .plist > Get Info > Targets, and make sure it is added to the correct target so it gets copied to device when installing. Darn had I figure that out soon enough I would have saved a lot of time. Hope this is helpful too. Regards!
只是为了补充。我遇到了同样的问题,建议的解决方案帮助我解决了问题,但是我不确定我是否真的使用了确切的解决方案。在我的情况下,问题是 .plist 文件被添加到不同的目标(之前添加了一个新目标)。因此,解决方案是 .plist > Get Info > Targets,并确保将其添加到正确的目标,以便在安装时将其复制到设备。该死的,如果我尽快弄清楚这一点,我会节省很多时间。希望这也有帮助。问候!
回答by Taimur Ajmal
If the file is not added in the resources folder and only placed in your documents directory. You can do this
如果该文件未添加到资源文件夹中,而仅放置在您的文档目录中。你可以这样做
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"file.plist"];
NSMutableArray *arrContentsplist = [[NSMutableArray alloc] initWithContentsOfFile:path];
回答by Mohit Gaur
This Code is working
此代码正在运行
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plist-name" ofType:@"plist"];
NSDictionary *Dictionary= [[NSDictionary alloc]initWithContentsOfFile:plistPath];
NSLog(@" current version CFBundleVersion = %@",[Dictionary valueForKey:@"CFBundleVersion"]);