Cant read data from plist

雨燕双飞 提交于 2020-01-05 12:30:23

问题


I am having trouble with reading data from my plist file. What is the correct way of extracting the values in a string? And lets say I have 2 items, how do I get both? Below will be the image on the plist.

And below is the source code for the plist. I read somewhere that there could be a difference with Xcode 3 and Xcode 4.

<?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>Array</key>
    <array>
        <string>value 1</string>
        <string>value 2</string>
    </array>
</dict>
</plist>

回答1:


First you need to get the path for the plist file resource in your application bundle:

NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"filename" 
                                                      ofType:@"plist"];

Given this path you can load the plist file into memory. This is quite simple since your root node of the plist file is an array:

NSArray* plist = [NSArray arrayWithContentsOfFile:plistPath];

More often the root node in your plist is a dictionary, dictionary has an equivalent convenience method for loading plists. If the root node is unknown then you should sue the NSPropertyListSerialization class, a bit more work but much more flexible.

The contents in memory of a plist will always be instances of the property value classes, use them as you would with any instances of them:

  • NSData
  • NSString
  • NSArray
  • NSDictionary
  • NSDate
  • NSNumber



回答2:


do reply about this still. But I managed to find a code that got it working for me already. The codes are below. Thanks peylow for your effort.

    NSString *path = [[NSBundle mainBundle] pathForResource:@"EventAddress" ofType:@"plist"]; 
    NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

    NSArray* allmyKeys = [myDictionary  allValues];
    NSLog(@"%@", allmyKeys);
    NSLog(@"%@", [[allmyKeys objectAtIndex:0] objectAtIndex:0]);

The last 2 NSLog is used to see if my plist does return an array of values and to find out the value of only 1 of them. And thanks a lot about the debugger, after looking at it for almost 3 days straight, I also realized my problem. The damn array isn't the normal one dimension, its TWO DIMENSION. Thats why I used objectAtIndex twice.



来源:https://stackoverflow.com/questions/7174281/cant-read-data-from-plist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!