Medha
Medha

Reputation: 39

Multi threading in iOS objective C

I have a doubt regarding multi threading in iOS objective C. I have never worked on threads.. In my app, I have a couple of tasks that need to run only in background so that the UI doesn't get freezed. Following is the code snippet,

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
            [self someFunctionCallinWebservice];
            dispatch_async(dispatch_get_main_queue(), ^(void){
                //UI Updates
            });
        });

In the above code, function : someFunctionCallinWebservice calls webservice for which I am using AFNetworking library. In the webservice if it is a success then I am saving the data locally. I am calling a function in success block to save the data sent from server like below,

[manager POST:url parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject){
[self functionToSaveData:someArray];
}

Here the someFunctionCallinWebservice is running in background but [self functionToSaveData:someArray] runs in foreground. Should I have this functionToSaveData also in background thread?

I mean if I am calling a function in background then all related functionalities of that function like, calling server, getting the data and saving it must also fall in background thread right? Why should I create another thread again?

Please help...

Upvotes: 0

Views: 6959

Answers (2)

Govind Prajapati
Govind Prajapati

Reputation: 957

Yes, u can call functionToSaveData function in background thread it will not create any issue but if u want to do any UI updates (like :-> reload tableView, show or hide some views) at that time u must do it on main thread otherwise it will not do any effect on your UI.

dispatch_async(dispatch_get_main_queue(),^{
    //Do any UI updates here 
});

Edit: Swift 4

DispatchQueue.main.async {
         //Do any UI updates here   
        }

Upvotes: 3

fishinear
fishinear

Reputation: 6346

Multi-threading is a large and difficult subject, for which iOS has different types of supports. I suggest you read Apple's Threading Programming Guide to start with.

For the type of action that you seem to be doing (fetching data from the internet), I suggest you use the iOS asynchronous APIs, such as URLSession, which remove the need to do anything with multi-threading yourself.

The answer to your concrete question depends on whether your POST:parameters:success: operation is a synchronous or an asynchronous operation, and it depends on what the functionToSaveData: actually does. Assuming that functionToSaveData: is intended to share the data with the rest of your app, it would be best to do it on the main thread, to avoid synchronisation problems.

Upvotes: 2

Related Questions