Can multiple (two) persistent stores be used with one object model, while maintaining relations from one to the other?

后端 未结 3 1954
滥情空心
滥情空心 2020-12-02 07:34

Introduction

My iOS project ships with a Core Data persistent store weighing some 160MB in SQLite format. There is a ton of grouped information in t

3条回答
  •  失恋的感觉
    2020-12-02 08:07

    The answer is yes. @Caleb points to the right resources, but getting it to work is still quite awkward. I thought I'd place a resumé here:

    For two NSPersistentStore instances to share the same model, you have to add a configuration to your model, which is a string-named subset of the entities:

    Model configurations

    In the model, to an entity that belongs to the second store, you add a fetched property (NSFetchedPropertyDescription for googlability). This is somewhat of a very simple stored procedure, and it could look like this:

    NSPredicate format for the fetched property

    Then, when you add the stores to your persistent store coordinator, you use the strings for the configuration argument (more info about the options here):

    [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 
                                              configuration:@"ModifyInBackground" 
                                                        URL:storeURL1
                                                    options:options
                                                      error:&error]
    
    [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType 
                                              configuration:@"ModifyInMain"
                                                        URL:storeURL2 
                                                    options:options 
                                                      error:&error]
    

    Finally, when you want to get from the entity in store B to the entity in store A, you trigger the fetched property like you would trigger a fault, just by accessing it.

    Note: A fetched property always returns an NSArray, because the predicate you write to establish the link might have multiple results. If you want to get to just one entity, you could place something like this in a wrapper method of your NSManagedObject subclass:

    Wallpaper *recordedWallpaper = [record.wallpaper lastObject];
    

提交回复
热议问题