Enhance Your Simple Table App With Property List

39 Flares 39 Flares ×

Here comes another weekly tutorial for iOS programming. We already built a very simple table app displaying list of recipes. If you look into the app, all our recipes are specified in the source code. I try to keep the thing simple and focus on showing how to create a UITableView. However, it’s not a good practice to “hard code” every item in the code. In real app, we used to externalized these static items (i.e. the recipe information) and put them in a file or database or somewhere else. In iOS programming, there is a type of file called Property List. This kind of file is commonly found in Mac OS and iOS, and is used for storing simple structured data (e.g. application setting). In this tutorial, we’ll make some changes in our simple table app and tweak it to use Property List.

In brief, here are a couple of stuffs we’ll cover:

  • Convert table data from static array to property list
  • How to read property list

Why Externalize the Table Data?

It’s a good practice to separate static data from the code. But why? What’s the advantage to put the table data into an external source. Let’s ask you to add 50 more recipes in our simple table app. Probably, you’ll go back to your code and put all the new recipes in the initialization:

1
2
3
4
5
6
7
8
    // Initialize table data
    tableData = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];
   
    // Initialize thumbnails
    thumbnails = [NSArray arrayWithObjects:@"egg_benedict.jpg", @"mushroom_risotto.jpg", @"full_breakfast.jpg", @"hamburger.jpg", @"ham_and_egg_sandwich.jpg", @"creme_brelee.jpg", @"white_chocolate_donut.jpg", @"starbucks_coffee.jpg", @"vegetable_curry.jpg", @"instant_noodle_with_egg.jpg", @"noodle_with_bbq_pork.jpg", @"japanese_noodle_with_pork.jpg", @"green_tea.jpg", @"thai_shrimp_cake.jpg", @"angry_birds_cake.jpg", @"ham_and_cheese_panini.jpg", nil];
   
    // Initialize Preparation Time
    prepTime = [NSArray arrayWithObjects:@"30 min", @"30 min", @"20 min", @"30 min", @"10 min", @"1 hour", @"45 min", @"5 min", @"30 min", @"8 min", @"20 min", @"20 min", @"5 min", @"1.5 hour", @"4 hours", @"10 min", nil];

There is nothing wrong doing this. But look at the code! It’s not easy to edit and you have to strictly follow the Objective C syntax. Changing the code may accidentally introduce other errors. That’s not we want. Apparently, it would be better to separate the data and the programming logic (i.e. the code). Does it look better when the table data is stored like this?

Sample Property List

Sample Property List

In reality, you may not be the one who provides the table data (here, the recipe information). The information may be given by others without iOS programming experience. When we put the data in an external file, it’s easier to read/edit and more understandable.

As you progress, you’ll learn how to put the data in server side (or what-so-called the Cloud). All data in your app are pulled from the server side on demand. It offers one big benefit. For now, any change of the data will require you to build the app and submit it for Apple’s approval. By separating the data and put them in the Cloud, you can change the data anytime without updating your app.

We’re not going to talk about the Cloud for today. Let’s go back to the basic and see how you can put all the recipes in a Property List.

What is Property List

Property list offers a convenient way to store simple structural data. It usually appears in XML format. If you’ve edited some configuration files in Mac or iPhone before, you may come across files with .plist extension. They are examples of the Property List.

You can’t use property list to save all types of data. The items of data in a property list are of a limited number of types including “array”, “dictionary”, “string”, etc. For details of the supported types, you can refer to the Property List documentation.

Property list is commonly used in iOS app for saving application settings. It doesn’t mean you can’t use it for other purposes. But it is designed for storing small amount of data.

Is it the Best Way to Store Table Data?

No, definitely not. We use property list to demonstrate how to store table data in an external file. It’s just an example. As you gain more experience, you’ll learn other ways to store the data.

Convert Table Data to Property List

That’s enough for the background. Let’s get our hands dirty and convert the data into a property list. First, open the Simple Table project in Xcode. Right click on the “SimpleTable” folder and select “New File…”. Select “Other” under “iOS” template, choose “Property List” and click “Next” to continue.

Xcode New Property List File

Create a New Property List File

When prompted, use “recipes” as the file name. Once you confirm, Xcode will create the property list file for you. By default, the property list is empty.

Xcode Recipe Plist

Empty Property List

There are two ways to edit the property list. You can right-click on the editing area and select “Add Row” to add a new value.

Xcode Property List Add Row

Add a New Row in Property List Editor

As we’re going to put the three data arrays in the property list, we’ll add three rows with “array” type. Name them with the keys: RecipeName, Thumbnail and PrepTime. The key serves as an identifier and later you’ll use it in your code to pick the corresponding array.

SimpleTableApp Property List Array

Define Three Arrays in Property List

To add data in the array, just expand it and click the “+” icon to add a new item. Follow the steps in the below illustration if you don’t know how to do it.

Add Property in Property List

Step by Step Procedures to Add an Item in Array

Repeat the procedures until you add all the values for the array. Your property list should look like this:

SimpleTableApp Recipe Property List

Recipe Property List

For your convenience, you may download the recipes.plist and add it to your project.

As mentioned earlier, the property list is usually saved in the format of XML. To view the source of the property list, right click and select “Open as Source Code”.

Open Property List as Source Code

View the Source Code of Property List

The source code of “recipes.plist” file will appear like this:

Property List Source Code

Source Code of Recipes.plist

Loading Property List in Objective C

Next, we’ll change our code and load the recipe from the property list we just built. It’s fairly easy to read the content of property list. The iOS SDK already comes with some built-in functions to handle the read/write of the file.

Replace the following code:

1
2
3
4
5
6
7
8
// Initialize table data
    tableData = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];
   
    // Initialize thumbnails
    thumbnails = [NSArray arrayWithObjects:@"egg_benedict.jpg", @"mushroom_risotto.jpg", @"full_breakfast.jpg", @"hamburger.jpg", @"ham_and_egg_sandwich.jpg", @"creme_brelee.jpg", @"white_chocolate_donut.jpg", @"starbucks_coffee.jpg", @"vegetable_curry.jpg", @"instant_noodle_with_egg.jpg", @"noodle_with_bbq_pork.jpg", @"japanese_noodle_with_pork.jpg", @"green_tea.jpg", @"thai_shrimp_cake.jpg", @"angry_birds_cake.jpg", @"ham_and_cheese_panini.jpg", nil];
   
    // Initialize Preparation Time
    prepTime = [NSArray arrayWithObjects:@"30 min", @"30 min", @"20 min", @"30 min", @"10 min", @"1 hour", @"45 min", @"5 min", @"30 min", @"8 min", @"20 min", @"20 min", @"5 min", @"1.5 hour", @"4 hours", @"10 min", nil];

with:

1
2
3
4
5
6
7
8
    // Find out the path of recipes.plist
    NSString *path = [[NSBundle mainBundle] pathForResource:@"recipes" ofType:@"plist"];    

    // Load the file content and read the data into arrays
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    tableData = [dict objectForKey:@"RecipeName"];
    thumbnails = [dict objectForKey:@"Thumbnail"];
    prepTime = [dict objectForKey:@"PrepTime"];

Behind the Code Change

Line #2 – Before reading the “recipes.plist” file, you have to first retrieve the full path of the resource.
Line #5 – You have defined three keys (RecipeName, Thumbnail, PrepTime) in the property list. In the example, each key is associated with a specific array, which is the value. In iOS programming, we use the term dictionary to refer to this key-value pair association. NSDictionary class provides the necessary methods for managing the dictionary. Here, we use the “initWithContentsOfFile” method of NSDictionary class to read the key-value pairs in a property list file.
Line #6-8 – These lines of code retrieves the corresponding array with the key we defined earlier.

Once you complete the change, try to run the app again. The app is the same as before. Internally, however, the recipes are loaded from the property list.

SimpleTable App with Custom Cell Prep Time

What’s Upcoming Next?

Again, I hope you learnt a ton through this tutorial. By now you should have a better idea about property list and how you can make use of it to store small amount of data. Next up, we’ll take a look at Storyboard and Navigation Controller.

As always, if you have any problem, leave comment below (or head to our forum) to share with us.

Update: You can now download the full source code of the Xcode project.

You May Like These:

Get Free Chapters of Our Swift Book

Beginning iOS 8 Programming with SwiftIf you want to create an app but don't know where to begin, this book covers the whole aspect of Swift programming and iOS 8 development and shows you every step from an idea to a real app on App Store. This book features a lot of hands-on exercises and projects. You will first create a simple app, then prototype an app idea, and later add some features to it in each chapter, until a real app is built. Want to learn more? Check it out here and get three free chapters.


  • Steven

    Another great insite to tables. How difficult is it to pull data from an XML file stored on another server. As u said earlier you would still need to submit this to the app store if u had a change.

    Any ref on this would be great

    Steve

  • agleung

    Thanks a bunch. I caught up with all your lessons. I feel like I am making progress leaps and bounds.

    FYI a typo in this lesson.

    Select “Other” under “iOS” template, choose “Property List” and click “Next” to continue.
    should read
    Select “Resource” under “iOS” template, choose “Property List” and click “Next” to continue.

    • http://www.appcoda.com Simon Ng

      Thanks for spotting the typo!

  • Sunny

    I have a question,
    can the value inside the property list change due to the action perform by end user??
    for example, if user tab on a cell, then the hit rate will change from 0 to 1 and so on…
    is it possible?

  • sunny

    I have a question here
    can the value inside the property list change due to the action performed by end user?
    for example if user tab on a cell, the hit rate will change from 0 to 1
    is this possible?

    • http://www.simonblog.com Simon Ng

      Yes, but you need to save it back to the property list file.

  • Pingback: 第六部分:应用Property List强化你的Simple Table应用程序 | EntLib.net 技术分享平台()

  • Josh Goodman

    Thanks for the awesome post, is there a way I can have my table data in a spread sheet and then read it in like that. This would be really useful for the app I am making.

    • http://www.simonblog.com Simon Ng

      Normally, you can store the table data in CSV (or XML) file format and load it in your app.

      • Josh Goodman

        Thanks, do you know where I could find a code sample of this?

  • Pingback: Improve the Recipe App With a Better Detail View Controller | iptips - iphone / ipad / ios / android / mobile / tutorials()

  • Pingback: Improve the Recipe App With a Better Detail View Controller | hatforrent()

  • Pingback: Improve the Recipe App With a Better Detail View Controller | t1u()

  • Shivank

    Heartly thanks to simon sir for great tutorial
    Sir please help me of fetching the data from server side
    its very urgent recently i am working on this so sir plsplsplsplsplsplsplspsl

  • Shivank

    Heartly thanks to simon sir for great tutorial
    Sir please help me of fetching the data from server side
    its very urgent recently i am working on this so sir plsplsplsplsplsplsplspsl

  • Toni Hardcastle

    hi, first i would like to say your courses are great and they have helped me a lot in making an app for my restaurant. i have successfully loaded the RBViewController with a plist in my web service but i have been stuck for days trying to make the detail view load but without any luck. i would appreciate if you could help me with this. thank you.

  • John

    fantastic tutorial simon. what would we need to do to update the data from plist on a server?

    • http://www.simonblog.com Simon Ng

      You’ll need to develop a simple server program that accepts request to update the data in plist file. Alternatively, you can check out http://www.parse.com that lets you easily save data in the backend.

  • http://binceipt.com/ Mark Thien

    this is outstanding ! Thanks a lot for your effort writing this great tutorial. Cheers !

  • Nate

    hey, thanks for the tutorial
    im just wondering how we would use this with the objects that we populated in the object oriented programming tutorial. like do we declare recipe with the Recipe class then do recipe.name = [dict objectForKey: name]; or something like that?

  • Karthik P

    Great set of tutorials to start with… especially with several pictorial examples…

  • http://twitter.com/_Nosaj Jason Solomon

    source code?

  • kitti

    Hi,

    I got message below, when i slide iPhone (emo)

    2013-04-16 22:10:21.256 SimpleTable[1167:f803] -[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x6e27390

    2013-04-16 22:10:21.263 SimpleTable[1167:f803] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x6e27390′

    *** First throw call stack:

    (0x13ca022 0x155bcd6 0x13cbcbd 0x1330ed0 0x1330cb2 0x2ac4 0xaec54 0xaf3ce 0x9acbd 0xa96f1 0x52d42 0x13cbe42 0x1d82679 0x1d8c579 0x1d114f7 0x1d133f6 0x1dae1ce 0x1dae003 0x139e936 0x139e3d7 0x1301790 0x1300d84 0x1300c9b 0x12b37d8 0x12b388a 0x14626 0x1ff2 0x1f65)

    terminate called throwing an exception(lldb)

    The code stop at

    cell.textLabel.text = [tableData objectAtIndex:indexPath.row];

    please help me.

    • kitti

      I try to change several think, i found that data in tableData is loss. I move declaration for tableData and initialize to local (in function), it’s fine.

      So, what’s wrong?

  • Ahmad Durrani

    thanks for this tutorial

    How we add the value(data) in a row in iOS plz help me

  • peter walsby

    hey great tutorial, just having trouble adding a row to the property list. When i open a new property list it has the default row with “root” as the key. I can’t seem to change the name of this and whenever i click add row nothing happens, i can add items to that “root” row and change it to an array etc but cant do anything else…

    • Heather

      thats because Xcode updated, in the version this tutorial uses you don’t see the root of the dictionary. I am working in a newer version of Xcode and it’s the same as yours, the plist automatically shows root. just add three rows beneath root, being the RecipeName, PrepTime, and Thumbnails arrays and keep all the coding the same and it will work. If you do this and look at the source code for the plist, you can see that it generates the same as the example provided in this tutorial

  • Untitled Entitled

    Thank you so much!

  • Mejdi K.

    This series of tutorials about Table views is one of the best on the whole Internet. You definitively made a great job right here Simon!
    Nonetheless, it would have been so nice to go a little bit further with 3 other tutorials:
    Part5 : Load data from database (with sqlite)
    Part6: Integration of the tableview in a nvaigation controller to see some details (stored in DB) about recipes
    Part7: Allowing to add/remove some recipes and refresh dynamically the table view

    I am wondering if I am not going to do so…

  • mwiggs

    When i replace the code to read from the property list, i get an empty basic list.
    As soon as i put the code back to defining the array manually, it works.
    I have downloaded the source files and replaced all of my h, m and xib files, but still no use.

    The source code works when i use it on its own.
    Any ideas ??

    • Tauphox

      I had the same problem. I found the problem for my project. When I named the properties list, I capitalized it when I should not have. To fix it, simply capitalize “recipes” in the line:
      NSString *path = [[NSBundle mainBundle] pathForResource:@”recipes” ofType:@”plist”];
      In SimpleTableViewController.m

  • CEMSOFT SOFTWARE

    thank you for this tutorial.

  • Insanim8

    Looks like it’s been a year or so since this was written, but since i just stumbled upon this, it’s new to me. Anyway, thanks for the plist primer. I had actually set up my plist exactly like this for my app. 3 arrays: names, values, and category. Each item within corresponding by Item number.

    My question is this: Setting it up this way has caused me to have a problem adding search functionality. When the user searches, the filtered array looks in the names array and redraws the table based on the text input. Unfortunately, the values and category arrays stay the same, so the corresponding items do not match any longer. So let’s say item13 in the name array was Lawnmower, the value was 6, and the category was Vehicle. When the user searches for “Lawn”, the lawnmower object is the first in the resulting table, but the value and category showing are for item0. I don’t know how to filter all 3 at the same time with this setup. Any suggestions? Besides not allowing a search. :)

    Thanks for the help.

  • Andrea Quintino

    I have created the Recipe “class”, and the array is only one “NSArray *recipes” with an instance for every recipe, like this:

    Recipe *recipe1 = [Recipe new];

    recipe1.name = @”Egg Benedict”;

    recipe1.prepTime = @”30 min”;

    recipe1.imageFile = @”egg_benedict.jpg”;

    recipe1.ingredients = [NSArray arrayWithObjects:@"2 fresh English muffins", @"4 eggs", @"4 rashers of back bacon", @"2 egg yolks", @"1 tbsp of lemon juice", @"125 g of butter", @"salt and pepper", nil];

    How can I retrieve the information from the plist file? It’s a bit different, I suppose

  • Pingback: Week 6 Reflection | m&m()

  • Damon Patron

    hi i was wondering if it is possible to do this exact tutorial but with videos that would be default to the app so even is there is no internet access they would still have these default videos loaded in their tableView

  • Bhavesh Bansal

    I know its been two years for this tutorial but i wanted to know something. I am designing music app in that i am using MPMediaQuery to query songs in user’s iPod library and i am storing all those songs in NSMutableArrray and then displaying with tableview but after reading this article i am getting confused that should i save all songs in plist and den display or shall i keep using nsmutablearray approach. Plz tell me which would be a better and reliable solution?…

  • Anita Agrawal

    Thanks for this tutorial.
    Can we add recipes at run time by the user,If user wants to add addition recipes in that?
    In this case how to store newly added recipes to plist programmatically?

    • http://www.appcoda.com/ Simon Ng

      In real app, we seldom use plist to store a large amount of data. In addition to that, plist is more appropriate for storing static data (e.g. configuration file). We use plist in this tutorial for demo purpose. If you want to add/delete recipes dynamically, you may use Core Data or store the data in the cloud. Check out this tutorial for details:

      http://www.appcoda.com/ios-programming-app-backend-parse/

  • leonguyenfs

    please help me

    when i replace the code

    // Find out the path of recipes.plist NSString *path = [[NSBundle mainBundle] pathForResource:@”recipes” ofType:@”plist”];

    // Load the file content and read the data into arrays
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    tableData = [dict objectForKey:@"RecipeName"];
    thumbnails = [dict objectForKey:@"Thumbnail"];
    prepTime = [dict objectForKey:@"PrepTime"];

    after
    i get an empty basic list. i tried replace much but not work @@

  • Kyle May

    This sucks

  • http://www.bublr.mx/ Cristian González

    I followed the tutorial, but now I can’t delete a row, when I tried it throws me an exception:

    Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object’

    What did I did wrong? I follow this tutorial and the one in the book, but I won’t work, haha. :( I made all my NSArray -> NSMutableArray.

  • Pingback: Cloud backend – IOS | Android Made Easy()

  • ed

    Love this tutorial and would love to see it updated for swift??

  • Anil Maharjan

    hello sir, i am trying to add row, but rather than adding row, its adding item within the root, i am not getting option to add recipename, thumbnail and preptime. Please help me to solve this prob as i am totally new in ios.

39 Flares Twitter 4 Facebook 26 Google+ 9 LinkedIn 0 39 Flares ×