2

Is there a way to retrieve an NSPersistentStore knowing its URL?

Something like:

NSURL *url = @"aaa\bbbb\ccc\xyz.sqlite"

NSPersistenStore *ps =[NSPersistentStore persistentStoreFromURL: url];

[self DoSomethingWith: ps];

** Obviously the method 'persistentStoreFromURL' doesn't exist!

Extra infos:

I know this store is loaded in some Coordinator (I don't know which one) and I have to remove it from its coordinator before migrating its data to another store. I only know the URL for this store.

I am using several coordinators at the same time. I want to avoid to loop through them and then loop again through all theirs stores to check if the store.URL is equal to url. This is the reason I am asking if it is possible to get the store directly from its url and then get its coordinator wihout all the looping.

4

2 回答 2

2

您可以通过以下方式从 Persistent Store Coordinator 获取当前商店:

    NSURL *url = @"aaa\bbbb\ccc\xyz.sqlite"
    NSPersistentStoreCoordinator *yourPSC = self.psc // Create or obtain reference to your psc

    NSPersistentStore *ps = [yourPSC persistentStoreForURL:url];

    [self DoSomethingWith: ps];

如果您不知道您的哪个 psc 包含 url 上的商店,请检查yourPSC.persistentStores是否包含具有相同 url 的商店。

像这样:

   for (NSPersistentStore *store in yourPSC.persistentStores) {
       if ([store.URL isEqual:url]) {
           [yourPSC removePersistentStore:store error:nil];
       }
   }
于 2014-03-27T12:46:21.460 回答
0

You have to initialize a NSPersistentStoreusing the designated initializer

initWithPersistentStoreCoordinator:configurationName:URL:options:

as described in Apple documentation

You will also need a store coordinator for this.

If you want to remove a store from a coordinator, though, you will need to have access to the coordinator, otherwise there is no way of removing it. You can ask the NSPersistentStorefor its persistentStoreCoordinator though. Migration of stores is also supported, depending on what you actually want to achieve. Note that a migration to another store might cause UI problems.

If you only have an URL you will need to ask a coordinator if it is assigned to the store. I see no other way out of the box.

于 2014-03-27T12:42:34.860 回答