Wednesday, June 22, 2016

Executing a method only once though it is getting called multiple times at once in Objective C

In my static variables in Objective C post, We have discussed static variables. In this post, Let's see how can you avoid a method getting called at the same time more than once using these static variables. 

This can help some times,

  1. In case of multi threading, Where there is a chance of same method getting called at once.
  2. In case of a clash between your auto refresh and manual pull to refresh.

Let's solve the second scenario using the static variables.

In my application, I have a manual refresh of notifications using tableview's pull to refresh and also a 5 minute timer event to fetch the recent notifications and for that I am using the below method.



 - (void)fetchNotificationsFromServer{

     Server call to fetch recent notifications(
               
      );       

 } 


What If this is a clash between the manual and timer refresh?

Obviously, We will end up with duplicate notifications. To avoid this we can use the static variable funda as shown below.



 - (void)fetchNotificationsFromServer{

    static BOOL functionISExecuting = NO;

     if(!functionISExecuting){

         functionISExecuting = YES;

      }

    else
        
        NSLog(@"Fetching notifications from server is in progress.......");          
        return;
        
    }

     Server call to fetch recent notifications(

          functionISExecuting = NO;
               
      );
       


 }



As static variable value doesn't change with in the scope of the method, We can check that value whether the method is already being called and in progress or not. After the service call, whether the call is successful or failure, We can roll back the value so that the next method call will be successful.


Hope this post is useful. Feel free to comment in case of any queries.




No comments:

Post a Comment