How do I start up an NSRunLoop, and ensure that it has an NSAutoreleasePool that gets emptied?
- by Nick Forge
I have a "sync" task that relies on several "sub-tasks", which include asynchronous network operations, but which all require access to a single NSManagedObjectContext. Due to the threading requirements of NSManagedObjectContexts, I need every one of these sub-tasks to execute on the same thread. Due to the amount of processing being done in some of these tasks, I need them to be on a background thread.
At the moment, I'm launching a new thread by doing this in my singleton SyncEngine object's -init method:
[self performSelectorInBackground:@selector(initializeSyncThread) withObject:nil];
The -initializeSyncThread method looks like this:
- (void)initializeSyncThread
{
self.syncThread = [NSThread currentThread];
self.managedObjectContext = [(MyAppDelegate *)[UIApplication sharedApplication].delegate createManagedObjectContext];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop run];
}
Is this the correct way to start up the NSRunLoop for this thread? Is there a better way to do it? The run loop only needs to handle 'performSelector' sources, and it (and its thread) should be around for the lifetime of the process.
When it comes to setting up an NSAutoreleasePool, should I do this by using Run Loop Observers to create the autorelease pool and drain it after every run-through?