简体   繁体   中英

How to make custom completion Handler with Objective-C

I've looked through various documents, but don't know how to apply the completion handler in the following cases.

//example function.
//default textView height 100.0f

-(void)getHeightResult{
  [self initHeight];
  NSLog(@"%@", [self setTextManager]);
}

-(NSString *)setTextManager{
   if(self.textView.frame.size.heigh != 100){
      return @"new Height";
   } else{
      return @"Default Height;
   }
}

-(void)initHeight{
   int result;
   for(int i = 0 ; i <= 20: i ++){
     result = result + i;
   }
   //result = 210
   self.textView.frame.size.height = result;
}

When executing the above functions, getHeightResult always outputs 'Default Height'. How can I apply a Completion Handler to get it returned as the value calculated in initHeight from a source like this?

We ask for answers to help you understand the Completion Handler, not for asking the actual source.

Code for completionHandler,

   - (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self getSize:^(bool status) {
        if (status == true) {
            // perofm your operioan
            NSLog(@"Done");
        }
    }];
}

typedef void (^CompletionBlock)(_Bool status);

-(void)getSize:(CompletionBlock)block{
    __block int count = 0;

    [self initWidth:^(bool status) {
        count++;
        if (count == 2) {
            block(true);
        }
    }];

    [self initHeight:^(bool status) {
        count++;
        if (count == 2) {
            block(true);
        }
    }];
}


-(void)initHeight:(CompletionBlock)block{
    int result;
    for(int i = 0 ; i <= 100; i ++) {
        result = result + i;
    }
    block(true);
}

-(void)initWidth:(CompletionBlock)block{
    int result;
    for(int i = 0 ; i <= 20; i ++){
        result = result + i;
    }
    block(true);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM