How to write the method to execute after completion of two methods (ios)

后端 未结 3 1099
说谎
说谎 2020-12-12 14:29

I have 2 methods to be executed on a button click event say method1: and method2: .Both have network calls and so cannot be sure which one will fin

相关标签:
3条回答
  • 2020-12-12 14:40

    You could just use a flag (aka a BOOL variable) that lets you know in either methods (A or B) if the other one has completed yet. Something on the lines of this:

    - (void) methodA
    {
        // implementation
    
        if (self.didFinishFirstMethod) {
            [self finalMethod];
        } else {
            self.didFinishFirstMethod = YES;
        }
    }
    
    
    - (void) methodB
    {
        // implementation
    
        if (self.didFinishFirstMethod) {
            [self finalMethod];
        } else {
            self.didFinishFirstMethod = YES;
        }
    }
    
    
    - (void) finalMethod
    {
        // implementation
    }
    

    Cheers!

    0 讨论(0)
  • 2020-12-12 14:42

    Neat little method I got from Googles iOS Framework they rely on pretty heavily:

    - (void)runSigninThenInvokeSelector:(SEL)signInDoneSel {
    
    
        if (signInDoneSel) {
            [self performSelector:signInDoneSel];
        }
    
    }
    
    0 讨论(0)
  • 2020-12-12 14:54

    This is what dispatch groups are for.

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    
    // Add a task to the group
    dispatch_group_async(group, queue, ^{
      [self method1:a];
    });
    
    // Add another task to the group
    dispatch_group_async(group, queue, ^{
      [self method2:a];
    });
    
    // Add a handler function for when the entire group completes
    // It's possible that this will happen immediately if the other methods have already finished
    dispatch_group_notify(group, queue, ^{
       [methodFinish]
    });
    

    Dispatch groups are ARC managed. They are retained by the system until all of their blocks run, so their memory management is easy under ARC.

    See also dispatch_group_wait() if you want to block execution until the group finishes.

    0 讨论(0)
提交回复
热议问题