Search code examples
iosobjective-ccore-data

IOS Use Core Data Only in Specific Parts of an app


I'm new to Core Data and trying to use it for persisting objects for offline support in an app communicating with JSON Back-end.

I was using NSObjects for my models and now use NSManagedObjects.

I only need to save these server objects in a few parts of the app, and in other parts, keep using the previous behavior, without persistence:

Fetch from server -> Parse JSON response -> Create Objects without persistence to Core Data -> Display in UI

For that purpose I was using initializers like this one

- (id)initObjectWithJSON:(NSDictionary *)JSONDictionary
{
  self = [super init];
  if (!self) {
    return nil;
  }
  self.property1 = JSONDictionary[@"property1"];
  self.property2 = JSONDictionary[@"property2"]
  ...

}

Do I now have to use the initializer initWithEntity:insertIntoManagedObjectContext: and thus create a new context even if I don't want to persist objects to core data?

Is there another approach to "separate" the objects which need persistence and the objects that don't need persistence to keep using the old methods like the one above?


Solution

  • Initialize it without a context:

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:myMOC];
    NSManagedObject *unassociatedObject = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
    

    Source: How to Deal with Temporary NSManagedObject instances?