在Objective-C中使用块

Jor*_*dan 3 objective-c objective-c-blocks

const char *sentence = "He was not in the cab at the time.";

printf("\"%s\" has %d spaces\n", sentence, (int) ^ {
    int i = 0;
     int countSpaces = 0;

    while (sentence[i] != '\0') {
        if (sentence[i] == 0x20) {
            countSpaces++;
        }
        i++;
    }    
    return countSpaces;
});
Run Code Online (Sandbox Code Playgroud)

这段代码只计算一个字符串中的空格,但由于某种原因,它表示1606416608个空格而不是8个.我不确定出了什么问题,所以感谢您的帮助!

Jes*_*der 9

您正在传递实际块printf,而不是块的结果.相反,试试吧

const char *sentence = "He was not in the cab at the time.";

printf("\"%s\" has %d spaces\n", sentence, (int) ^ {
    int i = 0;
    int countSpaces = 0;

    while (sentence[i] != '\0') {
        if (sentence[i] == 0x20) {
            countSpaces++;
        }
        i++;
    }    
    return countSpaces;
}()); // <-- note the extra parentheses here, indicating that you're calling the block
Run Code Online (Sandbox Code Playgroud)