How to delete all records in Coredata while keeping the storage type NSInMemoryStoreType. Want it to happen in XCTest

I am trying to unit test the main helper data classes, so in my setUp function, I create a basic data db in memory by creating NSManagedObjectContext

with this code:

+ (NSManagedObjectContext *)managedObjectContextForTesting {
    static NSManagedObjectContext *_managedObjectContext = nil;
    if (_managedObjectContext == nil) {
        NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];

        NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Buddyup" withExtension:@"momd"];
        NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

        NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];

        [psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:nil];

        [moc setPersistentStoreCoordinator:psc];

        _managedObjectContext = moc;
    }
    return _managedObjectContext;
}

      

I can only find how to delete master data records if saved to disk. The usual answer is you need to delete persistent storage. So I tried to follow and tried:

+(void)flushDataBase
{
    NSError * error;

    NSManagedObjectContext * moc = [ManagedObjectContextTesting managedObjectContextForTesting];
    NSPersistentStoreCoordinator* psc = [moc persistentStoreCoordinator];
    [moc lock];
    for(NSPersistentStore *store in [psc persistentStores]) {
        [psc removePersistentStore:store error:nil];

         //this line will throw an error because store.URL looks something like "memory://12345"
        [[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:&error]; 

    }
    [psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:&error]; 
    [moc unlock];

}

      

flushDataBase

called in the tearDown method. It doesn't work because when it hits the removeItemAtPath line it throws an error   error: -[UserCoreDataTests testGetUserWithId_ReturnsNothing] : *** -[NSFileManager fileSystemRepresentationWithPath:]: nil or empty path argument

This is because store.URL is looking for something "memory: // 12345" instead of "User: // directory". This means that the persistence storage url points to some place in memory. So how do you delete a storage item in RAM?

+3


source to share





All Articles