Reputation: 662
So I am making a framework to hold all the code used to manipulate a core data database. What I have ended up having an issue with is this.
I have a method which returns a new item
- (NSManagedObject *)createItem;
once they have modified that item the would call
- (void)save;
This has to be able to be executed in multiple threads so the managed object I return from my method has to have an NSManagedObjectContext consistent inside a thread. My solution to solve this was to create a NSMutableDictionary to hold a references to NSManagedObjectContexts using
[NSThread hash]
as the key. This works great. The only problem is that I cannot get rid of the contexts once their threads have finished.
Does anyone have any idea on how I could detect that?
Here is the code for my managed object context method
// Return Managed Object Context for Framework
- (NSManagedObjectContext *)managedObjectContext
{
// Get Thread Hash Value
NSThread * currentThread = [NSThread currentThread];
NSNumber * hashValue = [NSNumber numberWithUnsignedInteger:[currentThread hash]];
// Get Context From Thread Hash
NSManagedObjectContext * context = [self.managedObjectContexts objectForKey:hashValue];
// Check Context Exists
if (!context)
{
// Create Managed Object Context With Persistent Store Coordinator In Main Thread
NSPersistentStoreCoordinator * coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:coordinator];
}
// Add Context To Available Contexts
[self.managedObjectContexts setObject:context forKey:hashValue];
}
// Return
return context;
}
Upvotes: 2
Views: 419
Reputation: 119031
Look at using the threadDictionary
available on each NSThread
. In this way you can easily get the MOC for a thread (or know if there isn't one) and the cleanup will be handled for you.
Upvotes: 2