Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we define auto increment attribute in core data?

Tags:

iphone

Hello I am using core data in my application, and want to set ID attribute in every entity as autoincrement. Is it possible in core data? Or I have to manually insert the entry and manage the increment programatically??

like image 611
Javal Nanda Avatar asked Nov 03 '10 05:11

Javal Nanda


People also ask

Can you set auto increment?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

Which type of fields can be set to auto increment?

Auto increment is used with the INT data type. The INT data type supports both signed and unsigned values. Unsigned data types can only contain positive numbers. As a best practice, it is recommended to define the unsigned constraint on the auto increment primary key.

Can I auto increment a column that is not a primary key?

There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. So you can indeed have an AUTO_INCREMENT column in a table that is not the primary key.

Is primary key always auto increment?

A primary key is by no means required to use the auto_increment property - it just needs to be a unique, not-null, identifier, so the account number would do just fine.


2 Answers

If you are thinking of the id for the primary keys then core data handles this for you. On each object there is an objectID property you can access to see it. When you create an object from the managed object context, core data assigns a temporary id. When you commit the changes from the managed object context, core data assigns a perminant id. I don't think it would be a good idea to manually try and set this.

Read this stackoverflow thread for more details.

like image 125
drekka Avatar answered Oct 02 '22 02:10

drekka


I used that way with NSFetchedResultsController:

first sorting:

fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: false)] 

Then in add object method:

// Minimum id value var recordID = 1 if let lastRecordID = fetchedResultsController.fetchedObjects?.first?.id {     recordID = Int(lastRecordID) + 1 }  let newRecord = Record(context: persistentContainer.viewContext) newRecord.id = Int32(recordID) 
like image 39
Nik Kov Avatar answered Oct 02 '22 01:10

Nik Kov