I found the issue. I had to create a build phase and add the plist files to it. That way when i use the pathToResource ofFile it has a file to find when i use the rest of the code.
Storing data from a plist file into an array
-
16-10-2022 - |
Question
I have spent all of yesterday trying to figure this out with no luck at all. Here is the code im working with.
NSString *path = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
NSArray *array = [NSArray arrayWithArray:[dict objectForKey:@"root"]];
for(int num = 0; num < 5; num++)
{
NSLog(@"my array:%@", array);
}
NSLog(@"items in my array: %lu", (unsigned long) [array count]);
Here are the views for the plist file im working with.
<plist version="1.0">
<dict>
<key>New item</key>
<string>hello</string>
<key>New item - 2</key>
<string>world</string>
<key>New item - 3</key>
<string>again</string>
<key>New item - 4</key>
<string>and</string>
<key>New item - 5</key>
<string>again</string>
</dict>
</plist>
This code does not return null like when i tried using an NSArray over the NSDictionary, but when i run it console does not print out any data retrieved from the plist. It just prints out:
my array:{}
my array:{}
my array:{}
my array:{}
my array:{}
items in my array: 0
If i try to print out dict by changing the NSLog to NSLog(@"my array:%@", array); i get this.
my array:(NULL)
my array:(NULL)
my array:(NULL)
my array:(NULL)
my array:(NULL)
items in my array: 0
Solution 4
OTHER TIPS
Everything you could print for such plist is NSLog(dict[@"new item"]);
Also you probably should use
for(int num = 0; num < array.count; num++)
{
NSLog(@"my array:%@", array[i]);
}
instead of
for(int num = 0; num < 5; num++)
{
NSLog(@"my array:%@", array);
}
Don't know what keys are in dictionary? No need to concern about keys in this case. Try this
NSString *path = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
if(dict.count != 0)
{
NSArray *array = [dict allKeys];
for(int num = 0; num < array.count; num++)
{
NSLog(@"my array item:%@", [dict objectForKey:array[num]]);
}
}
else
{
NSLog(@"Your dictionary is empty.");
}
Are you trying to put all the values form the dict into the array ? If so add:
NSArray *array = [NSArray arrayWithArray:[dict allValues]];
//Check for file;
NSString *path = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:path])
NSLog(@"NO FILE AT PATH: %@", path);