0

I have categories on my entities that allow me to parse JSON into an entity:

- (id) populateFromJson: (NSDictionary *) json {
   ...
}

So then using MagicalRecord I can do this:

MyEntity *e = [My MR_createInContext:localContext];
[e populateFromJson:json];

However after I parse that into an entity I need to check if it already exists in the main context, ie check for duplicates. If it already exists in the main context I do not want to insert it into the context, however I cannot find a way using MagicalRecord to create an entity as part of a context, but don't insert into that context.

ie in core data you can do this:

MyEntity *e = [[MyEntity alloc] initWithEntity:[NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:[NSManagedObjectContext MR_defaultContext]] insertIntoManagedObjectContext:nil];

Where you pass nil to the context to insert into.

Then later if not a duplicate you can:

[localContext insertObject:e];

Am I missing something or is there not a way to do this in MagicalRecord?

lostintranslation
  • 23,756
  • 50
  • 159
  • 262
  • Your `MyEntity *e = [[MyEntity alloc] initWithEntity ...` creates the object without inserting it into the context. This object is *not* "part of the context" as your preceding text implies. You can call all Core Data methods even when using MagicalRecord, but I assume that you would get the identical result with `MyEntity *e = [My MR_createInContext:nil]` . – Martin R Dec 16 '14 at 14:49
  • MyEntity *e = [My MR_createInContext:nil] throws an exception. This is because MR tries to use nil as the context for the entity as well as the context to insert into. My code only uses nil as the context to insert into. – lostintranslation Dec 17 '14 at 02:02

1 Answers1

1

It's probably simpler to just not create the object at all if there is a duplicate. If you have the primary key in JSON, for instance, you could do a fetch for an object with that primary key (of course, your primary key attribute needs to be something you create) before you create it.

Andy Riordan
  • 1,154
  • 1
  • 8
  • 13
  • I think you are right. Unfortunately there is no way just to create a plain old object that is not attached to a context. Which is really what I want to do in my case, marshall the json into an object so I can access properties of the object to see if its a dup. In my case I will have to manually pull a few properties, check for dup then create the entity and marshall the json into the entity. Duplicates a little work but probably the 'best' way with the way the core data api works. – lostintranslation Dec 17 '14 at 02:05
  • It appears you can create an object without a context, and call `insertObject:` on the context later, once you're sure the object doesn't already exist. http://stackoverflow.com/a/3868651/131779 I have never tried this, so I can't vouch for it, but it's worth a shot. – Andy Riordan Dec 17 '14 at 04:08