4

my question is how can I use dbaccess framework with existing sqlite database? I have "test.sqlite" file in my device's Documents folder. I even renamed it to "test.db". When I try to commit the object of my class Worker nothing happens (I don't get any errors with databaseError(error: DBError!) method).

This is how Worker.swift looks like:

@objc(Worker)

class Worker: DBObject {
   dynamic var lastName: NSString?
}

This is how AppDelegate.swift looks like:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    DBAccess.setDelegate(self)
    DBAccess.openDatabaseNamed("test")

    var w = Worker.new()
    w.lastName = "WorkerName"
    w.commit()

    return true
}
Marina
  • 1,177
  • 4
  • 14
  • 27

1 Answers1

1

Yes you should be able to, but there will be some caveats. So DBAccess always has to have an ID column, so it will create one of those in your existing tables. It will also generate it's own PK values for existing records as well.

The reason your items are not persisting may lay in the fact that you will need to make a call to persistSynthesizedProperties, setting it to true on the delegate.

As you only have one single field, I can understand why this might appear to be doing nothing. Because when we swap out the getter/setter method in a swift class it requires different methods. These are the same methods as when an objc class has synthesised properties that require persisting.

So when the call to commit is made, there are no columns listed to persist, so it issues an update with no changes, which naturally is optimised out too a null operation.

We, in time, would like to do away with this delegate method, but at present we are unable to work out in obj-c what language a class is implemented using. If we can find a way, then we could do away with this rather annoying and weird quirk.

Thanks Adrian

Adrian_H
  • 1,548
  • 1
  • 14
  • 27
  • Thanks Adrian! I'll try it. But I have another question. How can I attach my class to existing table? What methods should I use? – Marina Aug 17 '15 at 19:49
  • So if I understand your question correctly, you name the class the same as the table, and you add in properties for every column. That should do it. – Adrian_H Aug 17 '15 at 20:19
  • I followed the guides that you gave. I added some properties to my class Worker. And I added this line of code: DBAccess.setPersistSynthesizedProperties(true). But it still saves the record neither in existing database nor in the new. – Marina Aug 18 '15 at 04:49
  • Probably the easiest thing here, Is if you can email us a small sample app and the database you are having issues with we will take a look. – Adrian_H Aug 18 '15 at 06:37
  • It is very nice of you. What e-mail can I use? – Marina Aug 18 '15 at 07:50
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/87260/discussion-between-marina-and-adrian-h). – Marina Aug 18 '15 at 10:47