Everyone who has developed a Titanium application is likely familiar with the Properties API, which allows you to store key/value pairs without needing to use a local SQL database to store that information. This is a great way to store a few configuration options, but once your application needs to store more than a couple values, storing each value individually can be a bit tedious.

However, if you combine the Properties API with Titanium’s built in JSON serialization capabilities, you can create a very flexible means of storing complex JavaScript objects. Let’s say we have a JavaScript object which contains user preferences for a game we’re writing in Titanium:

So we have quite a bit of configuration information about our user, and the structure is complex enough where it would be annoying to have to model it in a relational database. This is the perfect situation to use JSON+Properties to store this information. To persist this JavaScript object, you would combine the two APIs like so:

This is using the built in JSON namespace to convert the userProfile JavaScript object to a string, and then storing that string in a property so we can access it later. To pull the data back out again, we do something very similar:

Now we have a fully hydrated JavaScript object to work with. The other benefit of using this approach over a SQL database or individual properties is that your data structure is easy to evolve. So if your user profile changes to allow additional properties, like:

You don’t have to worry about migrating your database or adding code to access additional properties – you can just start using those properties in your code right away (bearing in mind that if you’re updating an app in production, those values will be undefined initially). It’s not rocket science, but this technique is just the ticket for storing complex objects without having to resort to a SQL database.

8 Comments

What are the disadvantages to using the properties API? My app has a list of 100+ objects that it needs to store locally for offline access and I’m trying to figure out the best way to do that. I’d love to just put it in Properties and not have to deal with creating and migrating tables, but I’m worried that Properties might not be as reliable or performant as the database? Or is that really not the case?

Kevin Whinnery

Posted June 9, 2010 @ 10:33 am

That’s a situation where a database will be a better solution – with that much data, you’ll get better performance from a database.

Masood

Posted June 9, 2010 @ 10:59 am

I have a related question. What is the best practice to store sensitive information e.g. password to a web service?