How to use Core Data models without saving them?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-29 10:16:12

You cannot just alloc/init a managed object, because a managed object must be associated with a managed object context. poster.posterID = ... crashes because the dynamically created accessor methods do not work without a managed object context. (Correction: As @noa correctly said, you can create objects without a managed object context, as long as you use the designated initializers. But those objects would not be "visible" to any fetch request.)

To create managed objects that should not be saved to disk you can work with two persistent stores: one SQLite store and a separate in-memory store.

I cannot tell you how to do that with MagicalRecord, but with "plain Core Data" it would work like this:

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

NSPersistentStore *sqliteStore, *memStore;

sqliteStore = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error];
if (sqliteStore == nil) {
    // ...
}
memStore = [coordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:&error];
if (memStore == 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:

Poster *poster = [NSEntityDescription insertNewObjectForEntityForName:@"Poster" inManagedObjectContext:context];
[context assignObject:poster toPersistentStore:memStore];
// or: [context assignObject:poster toPersistentStore:sqliteStore];
poster.posterID = ...;
poster.artists = ...;

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. I think that objects that are not assigned explicitly to a store are automatically assigned to the first store, which would be the SQLite store in this case.

I haven't worked with MagicalRecord yet, but I see that there are methods MR_addInMemoryStore and MR_addSqliteStoreNamed, which would be the appropriate methods for this configuration.

paulmelnikow

You could also try using the designated initializer -initWithEntity:insertIntoManagedObjectContext: with nil for the second parameter. (In my experience, some aspects of managed objects work fine without a context; others do not.)

There's a bit of further explanation in this answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!