简体   繁体   中英

How to call block from outside its declaration?

Hello I have following requirement.

I want to call completion block after the delegate method triggered.

Please find bellow sample snippet as example.

typealias CompletionBlock = (_ result: NSData?, _ error: NSError?) -> Void

 func Method1(block:CompletionBlock) 
{ 
   //SOME CODE
}

func Method2
{
    Completion(data,error)
}

Method2 is my delegate method. So when I call Method1 from some other class it will enter into block once pointer is on Method2

You can create one property like this,

var completionBlock : CompletionBlock!

Now on Method1

func Method1(block:CompletionBlock) { 
   self.completionBlock = block
}

on Method2

func Method2 {
    self.completionBlock(data,error)
}

I have not tested this code, but implemented like this in one of my application. Hope this may help you.

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