Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27191

Magical Records how to create just one unique entity

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)?

Upvotes: 3

Views: 1316

Answers (2)

Wagner Sales
Wagner Sales

Reputation: 1558

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

}

Upvotes: 2

Yuriy Panfyorov
Yuriy Panfyorov

Reputation: 523

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];
}

Upvotes: 1

Related Questions