How do I start up an NSRunLoop, and ensure that it has an NSAutoreleasePool that gets emptied?
Posted
by Nick Forge
on Stack Overflow
See other posts from Stack Overflow
or by Nick Forge
Published on 2010-05-14T09:45:33Z
Indexed on
2010/05/14
10:04 UTC
Read the original article
Hit count: 354
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 NSManagedObjectContext
s, 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?
© Stack Overflow or respective owner