Quick NSDictionary and plist example

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];

2 Responses to “Quick NSDictionary and plist example”

  1. echelon says:

    Thanks Paul – that was a help to me, working out how to load plist files – thx!

  2. Magic Bullet Dave says:

    Hi Paul,

    This is a great help. I’m wanting to go a little further and have been struggling to get going. Essentially I have a plist which has a root and 34 children each of type dictionary. Each child has a Name, Description and Image key (all strings). I can open the plist and read the contents into my NSDictionary object. I want to be able to set the contents of another dictionary object to the child dictionary.

    I am trying to populate a ListView with each row containing some text and an image.

    Any clues?

    Best regards

    Dave

Leave a Reply