简体   繁体   English

如何从.plist文件读取数据结构到NSArray

[英]How to read data structure from .plist file into NSArray

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 非常感谢你

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. 如果没有,可能是文件未添加到您正在构建的目标中,如果您有多个目标,则很容易犯错误。

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, ie 我有这个问题,但它没有工作,因为我把pList的结果放入一个数组,它应该是一个字典,即

NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"VehicleDetailItems" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];

Use this code if the plist is in the resources folder of the project. 如果plist位于项目的resources文件夹中,请使用此代码。

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

Kendall is correct. 肯德尔是对的。

In my experience, you need to add your file to the "Resources" folder in xcode. 根据我的经验,您需要将文件添加到xcode中的“Resources”文件夹中。

For completeness, Kendall and bentford are completely correct. 为了完整起见,Kendall和bentford是完全正确的。 However, in my sample, contentArray was a property and by the end of the method it was going out of scope because arrayWithContentsOfFile creates an auto-released object. 但是,在我的示例中,contentArray是一个属性,并且在方法结束时它超出了范围,因为arrayWithContentsOfFile创建了一个自动释放的对象。

To make this work correctly I needed to do 3 things: 为了使这项工作正常,我需要做三件事:

  1. put the file in the resources folder 将文件放在资源文件夹中

  2. name the file correctly (was leagues.plist instead of league.plist) 正确命名文件(是leagues.plist而不是league.plist)

  3. read the file using [[NSArray alloc] initWithContentsOfFile:plistPath)]; 使用[[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函数中释放。

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). 在我的情况下,问题是.plist文件被添加到另一个目标(之前添加了一个新目标)。 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. 因此,解决方案是.plist>获取信息>目标,并确保将其添加到正确的目标,以便在安装时将其复制到设备。 Darn had I figure that out soon enough I would have saved a lot of time. 我很快意识到这一点,我会节省很多时间。 Hope this is helpful too. 希望这也有帮助。 Regards! 问候!

If the file is not added in the resources folder and only placed in your documents directory. 如果文件未添加到resources文件夹中,并且只放在文档目录中。 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];

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM