Concurrent networking in iOS5
NSURLConnection
NSURLRequest
NSURLResponse
require a lot of boilterplate code
in iOS5,
+(void)sendAsynchronousRequest:(NSURLRequest*)requestqueue:(NSOperationQueue*)queuecompletionHandler:(void(^)(NSURLResponse*,NSData*,NSError*))handler;
so,
//Create the request NSURL*url=[NSURLURLWithString:@"https://the.api.com/method/"]; NSMutableURLRequest*request=[NSMutableURLRequestrequestWithURL:url]; //Create the queue NSOperationQueue*queue=[[NSOperationQueuealloc]init]; queue.name=@"com.your.unique.queue.name"; [NSURLConnectionsendAsynchronousRequest:requestqueue:queuecompletionHandler:^(NSURLResponse*response,NSData*data,NSError*error){ //If there was an error getting the data if(error){ dispatch_async(dispatch_get_main_queue(),^(void){ //Display error message in UI }); return; } //Do stuff with the data dispatch_async(dispatch_get_main_queue(),^(void){ //UpdateUI }); }];
NSManagedObjectContext
-(id)initWithConcurrencyType:(NSManagedObjectContextConcurrencyType)ct;
-(void)setParentContext:(NSManagedObjectContext*)parent;
-(void)performBlock:(void(^)())block;
Set your main context to execute on Main Queue (NSMainQueueConcurrencyType)
Create an import context and tell Core Data to create a new queue for it (NSPrivateQueueConcurrencyType)
Set the main context as the import contexts parent Context
On the import context, call perform Block and do the import (i.e.down load data, validate it, import it, purge old data etc)
Save changes on the import context. This will stage it up one level (to the main context )
Save changes on the main context. This will persist it on the associated persistent store (and update NSFetchedResultControllers etc)
//Set up the main context(probably in the AppDelegate) [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
NSManagedObjectContext *importContext=[[NSManagedObjectContextalloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType]; importContext.parentContext=self.managedObjectContext; [importContext performBlock:^{ //Download data,import etc.. NSError* importError=nil; [importContext save:&importError]; [importContext.parentContext performBlock:^{ NSError*parentError=nil; [importContext.parentContext save:&parentError]; }]; }];