如何从声明外部调用块​​?

时间:2022-09-24 23:14:06

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

Method2是我的委托方法。因此,当我从其他类调用Method1时,一旦指针在Method2上,它将进入块

1 个解决方案

#1


7  

You can create one property like this,

你可以创建一个这样的属性,

var completionBlock : CompletionBlock!

Now on Method1

现在在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.

我没有测试过这段代码,但是在我的一个应用程序中实现了这样的代码。希望这可以帮到你。

#1


7  

You can create one property like this,

你可以创建一个这样的属性,

var completionBlock : CompletionBlock!

Now on Method1

现在在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.

我没有测试过这段代码,但是在我的一个应用程序中实现了这样的代码。希望这可以帮到你。