views:

558

answers:

4

Is there any way to define relationship among tables and give foreign keys among them while using sqlite in Objective c

+2  A: 

you can use foreign keys in sqlite the same way as in other sql-datebase systems but be aware that foreign key constraints in sqlite are not checked/enforced!

codymanix
+1  A: 

SQLite isn't a "real" relationnal-database, you can have fields that link to other tables primary key, but you have to control all from your code. Same for deleting, no CASCADE or other integrity controls.

Clement Herreman
Any sample code available? I want to do it programmatically using Objective-c
I don't know objective-C, only SQLite.You have 1 field pk_table1 in a table "table1" ans 1 field fk_table1 in a table "table2". If you update your "fk_table1", in your Objective-C code, you check that the new value exist in "pk_table1", and so on...Haven't found any other way to do it.
Clement Herreman
A: 

you can define foreign key relations in sqlite like in any other sql database system but to actually enforce them you need additional triggers. these can be compiled automatically from the database scheme with a tool shipped with the official sqlite distribution.

the big advantage of this solution is that it is programming language agnostic. once setup you don't have to care about the triggers in your source code anymore. see http://www.sqlite.org/omitted.html for more information.

sebasgo
A: 

If you use the Cocoa CoreData framework, and define a managed object model, using SQLite as the persistent store - you can specify the relations between your model, and specify deletion rules ( such as cascade or deny ) and these will be performed and validated as you make changes to your entities from Objective-C, and committed back to the database when you save.

The relationships and rules are very similar to database foreign key rules, but are performed by the CoreData framework inside the objective-C runtime. The SQLite database is just used as a persistence store for your managed object graph.

Here is the CoreData programming guide at the Apple Developer Site:

NB This framework is Cocoa-specific, and your question doesn't explicitly mention using Cocoa, just Objective-C

cms