在 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/