objective-c - 将 Swift block 转换为 Objective-C block

标签 objective-c xcode swift closures

在 Swift 中,我创建了一个闭包方法(我认为):

func firstMove(action: UIAlertAction!) {
        if action.title == "Yes" {
            currentPlayer = "X"
        } else {
            currentPlayer = "0"
        }

我传递给这个 UIAlertAction 方法:

let optionToStartController = UIAlertController(title: "", message: "Do you want first move?", preferredStyle: .Alert)
            optionToStartController.addAction(UIAlertAction(title: "Yes", style: .Default, handler: firstMove))

如何将闭包和方法都转换为 Objective-C?

我试过:

- (void)firstMove:(UIAlertAction*)action
{
  if ([action.title isEqual: @"Yes"]) {
    _currentPlayer = 'X';
} else {
    _currentPlayer = 'O';
 }
}

然后像这样传递它:

UIAlertController *optionToStartController = [UIAlertController alertControllerWithTitle:@"" message:@"Do you want first move?" preferredStyle:UIAlertControllerStyleAlert];
[optionToStartController addAction:[UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler: firstMove]];

最佳答案

您可能正在寻找 block ,这是 Objective-C 中闭包的粗略等价物。我不太确定您要完成什么,但以下代码定义了 block firstMove 以及如何传递和从方法 addAction 调用它。

void(^firstMove)(int) = ^(int x){
    NSLog(@"print y: %d", x);
};

[self addAction:firstMove];

...

-(void)addAction:(void(^)(int))y{
    y(5);
}

关于objective-c - 将 Swift block 转换为 Objective-C block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38166683/

相关文章:

Xcode 中的 iOS 应用程序内存使用量不断上升

ios - 如何用另一个 UIView 的矩形切割 UIView 的顶角

ios - 如何从 NSString 中捕获最后 4 个字符

ios - 如何在 iOS 上的 Swift 中保存和恢复图形上下文?

ios - SSKeychain 凭证存储设置不正确?

iphone - Objective-C Protocol Madness——如何根据协议(protocol)返回对象?

ios - 获取设备类型/型号

iphone - 如何同时从iPhone中的URLS解析XML

xcode - NSLocalizedString 应该直接用于导出 XLIFF?

swift - CommonCrypto 如何在 SWIFT3 中使用?