SQL and oop in objective-c -


this stupid question, tried looking similar post couldn't find if there's some.

i'm starting use sql, it's quite easy how can save entire object in it?

i try explain better. if want save instance of "car" object should save primitive values or there way save entire object?

also, sql software guys suggest use? tried mac embedded sqlite

a couple of thoughts:

  1. if you're going sqlite programming in objective-c, should consider fmdb. makes sqlite programming easier.

    generally, though, core data preferred object persistence technology.

  2. but assuming wanted save object in sqlite table, can store object in database blob creating archive , saving in database:

    • create archive (see archives , serializations programming guide):

      car *car = [[car alloc] init]; car.make = @"honda"; car.model = @"accord"; car.year = 1998;  nsdata *data = [nskeyedarchiver archiveddatawithrootobject:car]; 

      but work, have implement initwithcoder , encodewithcoder methods car class described in encoding , decoding objects section:

      - (nsarray *)propertynames {     return @[@"make", @"model", @"year"]; }  - (id) initwithcoder:(nscoder *)adecoder {     self = [super init];     if (self) {         (nsstring *key in [self propertynames]) {             [self setvalue:[adecoder decodeobjectforkey:key] forkey:key];         }     }      return self; }  - (void)encodewithcoder:(nscoder *)acoder {     (nsstring *key in [self propertynames]) {         [acoder encodeobject:[self valueforkey:key] forkey:key];     } } 
    • you can save blob in database. use sqlite3_bind_blob or, easier, use fmdb:

      nsstring *documentspath = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes)[0]; nsstring *path          = [documentspath stringbyappendingpathcomponent:@"cars.sqlite"];  fmdatabase *database = [fmdatabase databasewithpath:path]; [database open]; [database executeupdate:@"create table if not exists cars (data blob)"]; [database executeupdate:@"insert cars (data) values (?)", data]; 
    • you can read database @ later point (using sqlite3_column_blob , sqlite3_column_bytes, or, again, using fmdb makes life easier):

      fmresultset *rs = [database executequery:@"select data cars"]; while ([rs next]) {     nsdata *cardata = [rs dataforcolumnindex:0];     car *carfromdatabase = [nskeyedunarchiver unarchiveobjectwithdata:cardata];     nslog(@"%@, %@, %d", carfromdatabase.make, carfromdatabase.model, carfromdatabase.year); } 
  3. having shown how store object blob, i'd discourage doing that. (lol). i'd encourage create sqlite data model mirrors object model, , store individual properties in separate columns of table.

or better, use core data.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -