Friday, May 6, 2011

NSDictionary and plist example

An example of creating NSDictionary object from plist file.
The plist provides the data to be filled in the NSDictionary object.
Following code fragment is collected from http://codersjunto.com/wp/?p=16
[NSDictionary and plist]

In your IPhone application add a New File/Other/Property List in my example MyTestList.plist. I then created three entries Name,Date,Debt and gave them some values.
In the code example below name, mydate, and debt are bound to labels on a view.


//Path get the path to MyTestList.plist
NSString *path=[[NSBundle mainBundle] pathForResource:@"MyTestList" ofType:@"plist"];
//Next create the dictionary from the contents of the file.
NSDictionary *dict=[NSDictionary dictionaryWithContentsOfFile:path];

//now we can use the items in the file.
self.name.text=[dict valueForKey:@"Name"] ;
NSLog(@"%@",[dict valueForKey:@"Name"]);
self.mydate.text=[dict valueForKey:@"Date"] ;
self.debt.text=[dict valueForKey:@"Debt"] ;
//change a value.
 [dict setValue:@"Jimmy" forKey:@"Name"];
//write changes back to file.
 [dict writeToFile:path atomically:YES];