3

I get some object from the server it is an json string. I want to create entity using keys and values from this string.

So I use this method for create entity using Magical Records

Entity *entity = [Entity createEntity];

I have id for each entity, so do I need to create some condition that will check if some entity already exist by id from code or there is alternative method in core data data model like in SQL (primary key etc)?

Matrosov Oleksandr
  • 25,505
  • 44
  • 151
  • 277

2 Answers2

2

I believe that after you create, you will want to use the entity.

- (Entity*)createEntity:(NSString*)id{

Entity * entity = [Entity MR_findFirstByAttribute:@"id" withValue:id];
if(! entity){
    Entity * newEntity = [Entity MR_createEntity];
    [newEntity setId:id];

    entity = newEntity
}

return entity

}

Wagner Sales
  • 1,448
  • 2
  • 10
  • 14
1

As one possible option, you can find out how many entities exist by using a predicate. For example:

NSUInteger numberOfEntities = [Entity countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"entityIdAttributeName == %@", entityId]];
if(numberOfEntities == 0) {
    Entity *entity = [Entity createEntity];
}
Yuriy Panfyorov
  • 523
  • 5
  • 5
  • Ok thanks i will try this method. So as i understood right there is no standard method to make entity unique using core data or magicalrecord? – Matrosov Oleksandr Nov 05 '13 at 22:00
  • Not in the way INSERT OR REPLACE would do, if you mean something like that. For possible solutions with unique primary keys, take a look at [this](http://stackoverflow.com/questions/901640/core-data-primary-key). – Yuriy Panfyorov Nov 06 '13 at 09:31