Loading an NSArray from a .plist file

人走茶凉 提交于 2019-12-24 07:19:23

问题


OK, so I know this question seems really basic, but I can't find a solution to my problem anywhere -

I have a .plist file within my project entitled 'feelings'. My plist file reads:

<plist version="1.0">
<dict>
    <key>feelings</key>
    <array>
        <string>Happy</string>
        <string>Sad</string>
    </array>
</dict>
</plist>

In the .m file under -(void)ViewDidLoad; I am trying to retrieve the contents of the plist using the following code:

NSString *path = [[NSBundle mainBundle] pathForResource:@"feelings" ofType:@"plist"];
NSArray *tempArray = [[NSArray alloc] initWithContentsOfFile:path];

self.feelingsArray = tempArray;
[tempArray release]; 

However I don't seem to be loading the array from the .plist file and executing the following code:

NSLog(@"feelings: %@", feelings); 

returns (null)

Can anyone figure out where I'm going wrong? It all seems fine to me, from what I've worked on before.


回答1:


Your top-level of the plist file is a dictionary, not an array. You should use NSDictionary instead of NSArray:

NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.feelingsArray = [tempDict objectForKey:@"feelings"];
[tempDict release];



回答2:


It returns a dictionary object not array,

NSString *path = [[NSBundle mainBundle] pathForResource:@"feelings" ofType:@"plist"];
NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:path];
NSLog(@"Feelings: %@",tempDict);
[tempDict release]; 


来源:https://stackoverflow.com/questions/7338531/loading-an-nsarray-from-a-plist-file

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