Atul Parmar Atul Parmar - 2 years ago 74
Swift Question

How to update specific record with specific fields dbAccess in swift

I have facing issue with update existing record (DBAccess ORM).
I want to update specific record by "ID" with specific fields.

Please review following swift code.

func updatePostDataById(Post_id: NSNumber, updatedName:String, updatedCity:String){

let objPost = Post();

objPost.Id = Post_id; = updatedName; = updatedCity;


When i try to update record in this way. then it has generate as new record in "post" table.

Please suggest perfect solution to fix this issue.

Answer Source

The OPs example will always create a new object because they are creating a brand new object using:

let objPost = Post();

To update a record, you need to get a hold of the original object, to do this you can either query for it, or use one of the shortcuts:

let objPost = Post.query().whereWithFormat("Id = %@", withParameters: [Post_id]).limit(1).fetch().firstObject;

or a slightly shorter version would be:

let objPost = Post.objectWithPrimaryKeyValue(Post_id)

Which essentially does the same query under the hood.

Both of these methods will return an existing object that whenever it is committed into the database, will replace the existing object.

Thanks Adrian

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download