Search code examples
iosobjective-ccore-datanspersistentstore

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


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.


Solution

  • You can get the current store from the Persistent Store Coordinator with:

        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];
    

    If you do not know which of your psc contain the store at url, check yourPSC.persistentStores for contains a store with same url.

    Like so:

       for (NSPersistentStore *store in yourPSC.persistentStores) {
           if ([store.URL isEqual:url]) {
               [yourPSC removePersistentStore:store error:nil];
           }
       }