How to write an Objective-C Completion Block

后端 未结 5 2066
萌比男神i
萌比男神i 2020-12-01 01:45

I\'m in a situation where need to call a class method from my view controller, have it do it\'s thing, but then perform some actions ONLY AFTER the class method has complete

5条回答
  •  情书的邮戳
    2020-12-01 02:31

    I wrote a completionBlock for a class which will return the values of a dice after they have been shaked:

    1. Define typedef with returnType (.h above @interface declaration)

      typedef void (^CompleteDiceRolling)(NSInteger diceValue);
      
    2. Define a @property for the block (.h)

      @property (copy, nonatomic) CompleteDiceRolling completeDiceRolling;
      
    3. Define a method with finishBlock (.h)

      - (void)getDiceValueAfterSpin:(void (^)(NSInteger diceValue))finishBlock;
      
    4. Insert previous defined method in .m file and commit finishBlock to @property defined before

      - (void)getDiceValueAfterSpin:(void (^)(NSInteger diceValue))finishBlock{
          self.completeDiceRolling = finishBlock;
      }
      
    5. To trigger completionBlock pass predefined variableType to it (Don't forget to check whether the completionBlock exists)

      if( self.completeDiceRolling ){
          self.completeDiceRolling(self.dieValue);
      }
      

提交回复
热议问题