gpt4 book ai didi

objective-c - 类型之间而不是变量之间的插入符,用括号括起来

转载 作者:行者123 更新时间:2023-11-30 17:14:26 24 4
gpt4 key购买 nike

我在浏览 Apple 的文档时看到了类似这样的内容 (void (^)(void))。有人能解释一下这句话的意思吗? ^ 是异或,对吧? void XOR void 对我来说没有多大意义?

还有类似 (void (^)(BOOL finish))

最佳答案

这些是向 Objective-C 添加匿名函数和函数对象的 block 。参见例如Introducing Blocks and Grand Central Dispatch :

Block objects (informally, “blocks”) are an extension to C, as well as Objective-C and C++, that make it easy for programmers to define self-contained units of work. Blocks are similar to — but far more powerful than — traditional function pointers. The key differences are:

  • Blocks can be defined inline, as “anonymous functions.”
  • Blocks capture read-only copies of local variables, similar to “closures” in other languages

声明 block 变量:

void (^my_block)(void);

为其分配一个 block 对象:

my_block = ^(void){ printf("hello world\n"); };

调用它:

my_block(); // prints “hello world\n”

接受 block 作为参数:

- (void)doSomething:(void (^)(void))block;

将该方法与内联 block 一起使用:

[obj doSomeThing:^(void){ printf("block was called"); }];

关于objective-c - 类型之间而不是变量之间的插入符,用括号括起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30335045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com