views:

155

answers:

3

Hi,

I wonder if it is possible to use KVC to generate SQL. I'm doing a light ORM; I wanna do something like this (pseudocode):

for key in object.getKeys
    sql = sql + formatField(key,objet.value[key]);

and get:

INSERT INTO Table (Field1) VALUES (1);

Is this possible in Objective-C?

A: 

Key Value Coding can't really do it, but you could use an NSDictionary for this task if you don't want to build a data access layer specific for your objects. Here's a quick example for numeric fields:

for ( NSString *key in [dictionary allKeys] )
{
    fields = [fields stringByAppendingFormat:@", %@", key];
    values = [values stringByAppendingFormat:@", %ld", (long)[[dictionary objectForKey:key] integerValue]];
}

NSString *sql = [NSString stringWithFormat:@"INSERT INTO Table (%@) VALUES (%@);", fields, values];
Marc Charbonneau
A: 

What you want sounds very similar to SQLite Persistent Objects. It's a set of objective-c classes that basically do what you're talking about. Details about the classes and the source (which may be particularly interesting to you if you want to write your own version) can be found here: http://iphonedevelopment.blogspot.com/2008/08/sqlite-persistent-objects.html

Adam Byram
A: 

I found class_copyPropertyList so that fill the bill.

I get that from SQLite Persistent Objects. I only need know how implement relations ;)

mamcx