Objective-C strange plist to dictionary behavior - objective-c

i have a really simple plist which is loaded into a NSDictionary. However, when i try to access a specific value, no data is available.
This is how my plist is structured:
edit* xml got messed up. You can take a look at it at pastebin:
http://pastebin.com/C419ZVeJ
Here i load the plist:
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [bundlePath stringByAppendingPathComponent:#"Test.plist"];
NSDictionary *metaPlistData = [NSDictionary dictionaryWithContentsOfFile:finalPath];
NSDictionary *meta = [metaPlistData valueForKey:#"meta"];
NSDictionary *assets = [meta valueForKey:#"sd"];
(i have removed the line where i access the key=1 entry)
When i inspect the "meta" dictionary and the "assets" dictionary in gdb, "meta" contains the required entries. However, assets always is nil. I am really lost here.. any ideas why? I load data from plists using this approach at other locations in my code and it has never been a problem.

On first blush, it looks like you're off by one layer in the hierarchy. "sd" isn't a key in the "meta" dictionary, it's a key in the "1" dictionary. Try this:
NSDictionary *meta = [metaPlistData objectForKey:#"meta"];
NSDictionary *one = [meta objectForKey:#"1"];
NSDictionary *assets = [one objectForKey:#"sd"];
Note too that you should be using -objectForKey: for dictionary access (-valueForKey: will probably work in this context but it belongs to the key-value coding mechanism which is something a little different.)
(Also, not sure if this is just a paste issue, but your plist looks incomplete.)

Related

Creating new NSStrings for each item in a plist array

I am attempting to create a class that takes each item in a Plist array and assigns them to an NSString for use in other classes in the program. Here's what I have so far:
NSString *appBundlePath = [[NSBundle mainBundle] bundlePath];
NSString *plist = [appBundlePath stringByAppendingString:#"/Contents/Resources/Values.plist"];
plistArray = [[NSArray alloc] initWithContentsOfFile:plist];
for (NSString* plistItem in plistArray) {
finalPlistString = plistItem;
}
NSLog(finalPlistString);
This code goes and finds the plist within the app bundle, assigns the contents of the plist to an NSArray and uses a for loop to set the plistItem NSString to the items in the plist array. Then the resulting string is logged using NSLog. It logs the last item in the plistArray, which makes sense because there is only one NSString variable to assign to.
How can I create a new NSString for each item in the plist array? If you are wondering, plistArray and finalPlistString are defined in the .h file.
First, the easiest way to get he path for a plist from a bundle is
NSString *path = [[NSBundle mainBundle] pathForResource:#"Values" ofType:#"plist"];
Second, after you read in the array, you now have all the strings in the array for further use in your program. So it takes you two lines of code to get all the data.
To access, say, the third item in the array, just use
plistArray[2]
-- there is nothing else you have to do, i.e. you do not even need a variable. E.g. to assign to a label you write
label.text = plistArray[2];
Your for loop below that does not make sense. To get the last item of an array, it is easier to do this:
NSString *lastItem = plistArray.lastObject;

How to use predicate with nsdictionary?

I have a dictionary within another dictionary in my plist as below:
<dict1>Root
<dict2>A
<dict3>Apple
<string>"About Apple..."
<dict3>Arrow
<string>"About Arrow..."
<dict2>B
<dict3>Ball
<string>"About Ball..."
<dict2>C
etc...
The user is currently using a search bar to search for a string. How can I look with the third level and compare each string using a predicate and return results and pass these to table view cells?
I tried following this video tutorial but I fail on the predicate.
https://www.youtube.com/watch?v=UE4h_Td6W6U
He has written his dictionary to an array from what I can see. Mine seems a little more complicated.
I am new to this so any help will be appreciated.
You need to traverse down your dictionary list until you get to the Dictionary that you're looking for. It looks something like this:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"YOURPLIST" ofType:#"plist"];
NSMutableDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath]; //This puts you into the root directory
NSMutableDictionary *secondLevel = [NSMutableDictionary dictionaryWithDictionary:[dictionary objectForKey:[NSString stringWithFormat:#"A"]]]; //or B or C etc
NSMutableDictionary *thirdLevel = [NSMutableDictionary dictionaryWithDictionary:[dictionary objectForKey:[NSString stringWithFormat:#"Apple"]]];
This will put you in the Apple dictionary, however to be able to fetch the string you need a key attached to it. Your dictionary should look like
<key>Some key name</key>
<string>About Apple...</string>
And then you could fetch the string using the key through:
NSString *string = [thirdLevel objectForKey:#"Some key name"];
If you're strictly searching for strings, you could do something like this Search String in NSDictionary store in NSMutableArray

Won't write to plist array Xcode. This was the code used and it doesn't work, does anyone know why?

NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"HighScore.plist"];
NSMutableArray* plistDict = [[NSMutableArray alloc]
initWithContentsOfFile:finalPath];
[plistDict addObject:[highScoreLabel text]];
NSArray *regArray = [NSMutableArray arrayWithArray:plistDict];
[regArray writeToFile:#"HighScore.plist" atomically: YES];
Does the file exist and contains valid data?
See Apple's documentation about NSMutableArray initWithContentsOfFile::
Return Value
An array initialized to contain the contents of the file specified by aPath or nil if the file can’t be opened or the contents of the file can’t be parsed into an array. The returned object might be different than the original receiver.
Discussion
The array representation in the file identified by aPath must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects). The objects contained by this array are immutable, even if the array is mutable.
If initWithContentsOfFile: returns nil, it's clear that the rest of the code won't work either.
p list write to file means to write the p list or to save the data ,,,for retrieving view write the content of file .

Get data from a PList into UITableView?

I want to maintain a list of records, for each one I maintain the same type of data. I want to use this data in 2 different places:
UITableView that takes from each record the "Name" value
UIViewController that takes all the data to use in different fields.
I assume I should be using a plist to store the data; I also assume that the object that should be receiving the data for the UITableView is NSArray so I can use the cellForRowAtIndexPath method to create the table automatically.
So i created the plist "PLForArr.plist":
It seems that i can only get a NSDictionary when calling the plist using
NSString *path = [[NSBundle mainBundle] pathForResource:#"PLForArr" ofType:#"plist"];
NSArray * myArr = [[NSArray alloc] initWithContentsOfFile:path]; //doesn't work...
NSDictionary * myDict = [[NSDictionary alloc] initWithContentsOfFile:path]; //does work, but who to I make a NSArray out of it / or get the data from here to the UITableView?
I understand that i don't understand something basic here... Can someone take me step by step on:
How to keep the data - should I use plist or something else? Should I have a main record of type array (as I did on the example plist here) or can I just keep it as these Dictionaries without the unnecessary MyArr that I used considering the UITableView end target?
How to call the data - Is there a way to get it into a NSArray or must it get into a NSDictionary?
How to call it into the the UITableView - Can I fill in the lines using a NSDictionary?
Storing the data is an Array or a Dictionary is up to you. But if you want to make changes to it over time you can't store it in the main bundle.
Your pList file is a dictionary that contains an array. See code example below.
You will have to store the dictionary in an array for the data source for your table. See code example below.
Assuming that your UITableView's data source is called tableArray. You can use tableArray to fill in the information in the table and your view. Oh yeah,
NSString *path = [[NSBundle mainBundle] pathForResource:#"PLForArr" ofType:#"plist"];
NSDictionary *myDict = [[NSDictionary alloc] initWithContentsOfFile:path];
NSArray *myArray = [myDict objectForKey:#"MyArray"];
self.tableArray = [myArray copy];
[myArray release];
[myDict release];
This goes in tableView: cellForRowAtIndexPath:
cell.text = [[tableArray objectAtIndex:row]objectForKey:#"Obj Name"];
Storing your data either in a dictionary, or in an array is up to you. Depending on the kind of data you have, you will consider storing unordered collection of objects (dictionary), accessing the entries with keys; or rather in ordered collection (array), using numeric indexes.
It's fine to get arrays from property list files, but the root (top level) object is a dictionary (in the screenshot, "MyArr" isn't the top-level object, it is the key for accessing your array in the top-level dictionary). To get your array from it, simply alloc/init the plist dictionary the way you did, and access the array entry using its key ([myDict objectForKey:#"MyArr"]). Otherwise make sure you set the root object of the property list to be an array, and retry NSArray's initWithContentsOfFile:
The real question seems to be How can I fill the cells with my data ? The table views ask its delegate and dataSource about how many sections, rows in a section, to display. Based on these numbers, it will ask the dataSource for cells. Once again depending on the storage type you've chosen, you will implements these methods a little bit differently, but the concepts remain.
You will probably want to read documentation about :
Property List
Table views

Objective-c: Initialize NSMutableArray with NSString that is plist structure

If I have a NSString that came back from a web service in the form of a plist structure, how can I initialize a NSMutableArray with this NSString. I want to know if there is a similar way to initWithContentsOfFile for NSString.
My first thought was to save the NSString to a file and then use initWithContentsOfFile; but I am trying to avoid save to file first. It seems like there should be a simpler way.
Untested, should work like this:
NSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding];
NSMuableArray *array = [NSPropertyListSerialization
propertyListWithData:data
options:NSPropertyListMutableContainers
format:NSPropertyListXMLFormat_v1_0
error:NULL];
See the Property List Programming Guide "Reading and Writing Property-List Data". It covers how to turn NSData into a property list. If you already have NSData from the network, just don't convert it to NSString. If you only have an NSString, use dataUsingEncoding: to convert it to NSData.
Check the documentation for the -propertyList and -mutableCopy methods.
You could use NSXMLParser to parse the XML (which is what a plist is) and turn it into a dictionary (and retrieve the array from there)