Jesse Bunch
Jesse Bunch

Reputation: 6679

CoreData - Computed Property in Background Thread

I am fetching about 2500 stars from CoreData to use in constructing a star map and would like to do most of the math for computing coordinates and such in a background thread for obvious reasons. My question is, since I have to pass the CoreData objects back to the main thread as NSManagedObjectIDs, how would you go about computing say, a set of cartesian coordinates in a background thread and (preferably) set those coordinates in the NSManagedObject subclass?

For what it's worth, here is a snippet of the code I'm using to fetch from CoreData and pass to the main thread:

// Context and Model
NSManagedObjectContext *context = [self.dataProvider newManagedObjectContext];
NSManagedObjectModel *model = [self.dataProvider sharedManagedObjectModel];

// Fetch the stars
NSArray *stars = [SkyObject getSkyObjectsBetweenMinCoords:minCoords 
                                                maxCoords:maxCoords 
                                                   minMag:self.minimumMagnitude 
                                                   maxMag:self.maximumMagnitude 
                                                    model:model 
                                                  context:context];

NSMutableArray *starIDs = [[NSMutableArray alloc] init];

// Add the star's objectID to the set
for (SkyObject *star in stars) {
    [starIDs addObject:star.objectID];
}

// Pass objects across thread boundaries
[self performSelectorOnMainThread:@selector(updateLocalContextWithObjectIDs:) withObject:starIDs waitUntilDone:YES];

// Release retained memory
[starIDs release];
[context release];

Upvotes: 0

Views: 242

Answers (2)

TechZen
TechZen

Reputation: 64428

You normally don't "pass the CoreData objects back to the main thread as NSManagedObjectIDs" but instead you would perform all your operations setting up the managed objects with a context running on the background thread and then when you are done, you would merge the foreground context with the background context.

Passing managedObjectIDs works of course but its a slow way to go about it especially if you have thousands of objects to process. It also doesn't update the entire object graph like a merge does.

Upvotes: 0

owen gerig
owen gerig

Reputation: 6172

i can tell from your question and code this is way above my head. but what about GCD. its what im using for a repeated keep alive being sent via tcp/ip. anyways hope it helps http://www.fieryrobot.com/blog/2010/06/27/a-simple-job-queue-with-grand-central-dispatch/

Upvotes: 1

Related Questions