将Swift块转换为Objective-C块

时间:2016-07-03 04:16:18

标签: 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]];

2 个答案:

答案 0 :(得分:0)

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

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

[self addAction:firstMove];

...

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

答案 1 :(得分:-1)

你可以看到这个例子。它应该正常工作。

    #include<stdio.h>
    int wordCount(char str[],int b);
    main()
    {
        char str[100];
        int b, d;
        clrscr();  // clear the screen every compile and build

        printf("Write your message: ");
        gets(str);   //reads the str[] which the user input
        b = strlen(str);  // run without the <string.h>

        d = wordCount(str,b);

        printf("No. of words: %d", d);

    getch();
    }

    int count(str[],b) // Where the error points out
    {
        int i=0,word=0;

        for (i = 0; i < b; i++)
        {
            if (str[i] != ' ' && str[i] != '\t')
            {
                word++;
                while (str[i] != ' ' && str[i] != '\t')
                {
                    i++;
                }
            }
        }
        return word;
    }