Search code examples
ioscore-datansmanagedobject

How to use entity with using managedObjectContext?


I don't want to save to persistence storage. How can i use entity class without saving to persistence storage?


Solution

  • After creating the managed object context and the persistent core coordinator, you assign two persistent stores to the store coordinator:

    NSPersistentStore *sqliteStore, *memoryStore;
    
    sqliteStore = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error];
    if (sqliteStore == nil) {
        // ...
    }
    memoryStore = [coordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:&error];
    if (memoryStore == nil) {
        // ...
    }
    

    Later, when you insert new objects to the context, you associate the new object either with the SQLite store or the in-memory store:

    Records *record = [NSEntityDescription insertNewObjectForEntityForName:@"Records" inManagedObjectContext:context];
    [context assignObject:poster toPersistentStore:memoryStore];
    // or: [context assignObject:poster toPersistentStore:sqliteStore];
    record.empID = ...;
    record.name = ...;
    

    Only the objects assigned to the SQLite store are saved to disk. Objects assigned to the in-memory store will be gone if you restart the application.