Core Data is a very powerful entity framework, it’s something very useful that saves a lot of time while working with complex data schemas and persistence.
Sadly there are still features that are missing, like and auto-increment option for a property of an entity.
Sometimes is very useful having an auto-increment property and one solution to do it is subclassing the method
awakeFromInsert that is called each time a new entity is created and inserted.
So this is the code for the magic (using an order field and MagicalRecord):
NSInteger tempID = ([[[MyObject MR_findAllSortedBy:@"order" ascending:YES] lastObject] order])?[[[[MyObject MR_findAllSortedBy:@"order" ascending:YES] lastObject] order] intValue]+1:0;
[self setOrder:[NSNumber numberWithInt:tempID++]];
It’s mandatory retriving the highest value of order inside the database, once this has been done, we can increment this value by one and then set it to our new entity manually.
This process of course works even without MagicalRecord and needs a couple of more steps with NSFetchRequest, but nothing too complicate.