Search code examples
iphoneiosnsthread

threading for network calls in iOS 5


I have been looking over the internet, but could not find the perfect tutorial for threading in iOS, currently i am working on iOS 5 , tutorial found on web were old, my app needs to fetch data from webservices, so I want to call network operation in a thread, I have a tabbar, in each tab it loads different type of data from web, as it start fetching data , I dont want my app to stuck on that tab, i want that user can navigate to other tab meanwhile its fetching data for that tab. how can it be possible

EDIT: I want to have a flow :

 //in a thread
 fetchDataFromWeb(){//during this call activity indicator
 //fetch and make an array of ojbects     
 }

when data is loaded trigger the populate funciton

laoddata(){//remove activity indicator
//load tableview and other views
}

how will i know my thread finished its process


Solution

  • Take a look to NSOperation, NSThread or Grand Central Dispatch

    Edit: NSThread example

    //on main thread on some action
     NSDictionary *myParameterDitionary = [..];
     [NSThread detachNewThreadSelector:@selector(aBackThreadMethod:) toTarget:self withObject:myParameterDitionary];
    
    //this is on back thread called
    - (void)aBackThreadMethod:(NSDictionary *)variablesDictionary{
        @autoreleasepool {
            //presess data
            NSDictionary *responseDictionary = [..];
            [self performSelectorOnMainThread:@selector(didABackThreadMethod:) withObject:responseDictionary waitUntilDone:YES];
        }
    }
    
    //call back on main thread
    - (void)didFinishABackThreadMethod:(NSDictionary *)responseDictionary{
       //do stuff ex update views
    }
    

    The @autoreleasepool is for ARC. If you use manual memory management you have to do:

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [pool release];