I have been playing around with an AIR application which stores data to a local SQLite DB. I have a very basic settings table which is nothing more than a key/value paring of settings. The keys all match up with variables in the Model. So, there’s a setting for “fontFamily” which is both the key and the Model variable name. I had the following basic settings:
- fontFamily (String)
- fontColor (uint)
- backgroundColor (uint)
- startAtLogin (Boolean)
The way SQLite works, it is just easier to store things as VARCHARs and convert them as needed, so how was I going to convert all of these?
My initial thought was to use a switch statement. That way I could cast each variable based on the key. That wouldn’t be so bad for this small amount of settings but it simply would not do for a larger application. I know that the data stored in the DB is going to be able to be converted to whatever data type I need (i.e. “true” can be converted to Boolean, “#FFFFFF” can be converted to uint, etc). So, I came up with this snippet of code that’s been working great for me so far. All settings are loaded into an acSettings ArrayCollection in the model initially so that is what I’m looping over:
if( Model.getInstance().acSettings.length )
{
var settingVO:SettingVO;
var className:Class;
for( var i:int = 0; i < Model.getInstance().acSettings.length; i++ )
{
settingVO = Model.getInstance().acSettings.getItemAt(i) as SettingVO;
className = Class( getDefinitionByName( getQualifiedClassName( Model.getInstance()[settingVO.key] ) ) );
Model.getInstance()[settingVO.key] = settingVO.value as className;
}
}
Piece by piece, here’s what happens:
- I first get the variable in the model correponding with the current setting key: Model.getInstance()[settingVO.key]
- Then I get the class name of the model variable with this: getQualifiedClassName( Model.getInstance()[settingVO.key] )
- Then I get the class definition with this: getDefinitionByName( getQualifiedClassName( Model.getInstance()[settingVO.key] ) )
- Finally, I cast that as a Class using Class( getDefinitionByName( getQualifiedClassName( Model.getInstance()[settingVO.key] ) ) );
The result is that I get whatever the classname of the variable is stored as a class in my “className” variable which I use in casting in a loop.
Just so you know there’s nothing else going on, my SettingVO class is nothing more than this:
package com.reynacho.Reminder.vo
{
[Bindable]
public class SettingVO
{
public var settingID : Number; // primary key
public var key : String;
public var value : String;
public function SettingVO (settingID:Number, key:String, value:String)
{
this.settingID = settingID;
this.key = key;
this.value = value;
}
}
}

Related Articles
No user responded in this post
Leave A Reply