Natarajan
Natarajan

Reputation: 3271

How to cleanup in-memory object graph of NSPersistentStoreCoordinator with NSInMemoryStoreType?

I'm using NSInMemoryStoreType for NSPersistentStoreCoordinator to maintain the entities and relationships in-memory as I don't want to write it to the disk.

So I'm planning to cleanup the in-memory object graph in certain point as the app memory is keep on increasing due to core data object references still in memory.

How to delete/reset/remove the whole core data entities and relationships from in-memory object graph to cleanup app memory usage?

Is there any optimized way to handle NSInMemoryStoreType and cleanup memory when needed?

Please Note: My app's deployment target is iOS 8.0 and above. So the cleanup API should be available for iOS 8 target as well.

Thanks!

Upvotes: 0

Views: 323

Answers (2)

Natarajan
Natarajan

Reputation: 3271

I've found a work around to cleanup the in-memory store context. This workaround is cleaning up some memory from the in-memory object graph and not everything.

    if inMemoryManagedObjectContext != nil{

        if let stores = inMemoryManagedObjectContext.persistentStoreCoordinator?.persistentStores{

            for store in stores{

                do{

                    try inMemoryManagedObjectContext.persistentStoreCoordinator?.remove(store)

                }catch{

                    print("Cleanup InMemoryManagedObjectContext error;\(error)")
                }
            }
        }

        inMemoryManagedObjectContext = nil
    }

Thanks Jon Rose: If I have to delete all entities, it'll give performance issue as I have more entities. Also I'm not sure that deleting entities will cleanup memory immediately.

Thanks Sandeep Bhandari: PersistentContainer is available for iOS 10 and above and My app should support from iOS 8.

Also Context reset is not making any impact in memory cleanup. And Please let me know, if there is any other way to cleanup in-memory context/persistentStoreCoordinator.

Thanks!

Upvotes: 0

Jon Rose
Jon Rose

Reputation: 8563

Just delete the entities like you would with any core-data setup.

Upvotes: 0

Related Questions