Obj-C 块可以自行执行吗?
这是这个问题的延伸: 是否可以在 Objective-C 中创建“Block”对象的类别。
基本上,虽然似乎可以通过 NSObject 或 NSBlock 在块上创建类别,但我无法理解块如何能够评估自身。最后一个问题的答案中给出的示例:
- (void) doFoo {
//do something awesome with self, a block
//however, you can't do "self()".
//You'll have to cast it to a block-type variable and use that
}
意味着可以以某种方式将 self 转换为块变量,但是如何执行块本身呢?例如,假设我在 NSBlock 上做了一个类别,并在一个方法中做了:
NSBlock* selfAsBlock = (NSBlock*)self;
是否有任何消息可以发送到 selfAsBlock 来评估块?
This is an extension of this queston:
Is it possible to create a category of the "Block" object in Objective-C.
Basically while it seems possible to create a category on blocks, either through NSObject or NSBlock, I'm having trouble understanding how the block would be able to evaluate itself. The example given in the answer to the last question:
- (void) doFoo {
//do something awesome with self, a block
//however, you can't do "self()".
//You'll have to cast it to a block-type variable and use that
}
Implies that it is possible to somehow cast self to a block variable, but how would one execute the block itself? For example, say I did a category on NSBlock and in a method did:
NSBlock* selfAsBlock = (NSBlock*)self;
Is there any message I can send to selfAsBlock to have the block evaluate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如下所示:
请注意(在大多数情况下)您需要修复块签名,以便编译器能够根据目标平台 ABI 设置调用站点。在上面的例子中,签名是返回类型
int
,单个参数类型int
。一个完整的例子是:
Like this:
Note that (in most cases) you need to fix the block signature so that the compiler is able to set up the call site according to the target platform ABI. In the example above, the signature is return type
int
, single parameter of typeint
.A full example is:
NSBlock
有一个invoke
方法,可用于调用该块。请注意,这是一个私有的、未记录的方法。
NSBlock
has aninvoke
method that can be used to call the block.Note that this is a private, undocumented method.