一块在编译时会发生什么,我可以在运行时创建一个吗? [英] What happens to a block at compile time, and can I create one at runtime?
问题描述
这是关于 Objective-C 中 blocks (^ {})的两部分问题.我已经搜索了一些答案,但是Google或SO中什么都没有显示.这个问题源于创建针对iOS的自定义XML布局引擎的愿望,该引擎具有对块的支持-这意味着我想在运行时解析NSStrings并创建一个块.
This is a two-part question about blocks (^{}) in Objective-C. I have searched for some answers, but nothing has showed up in Google or SO. This question stems from a desire to create an custom XML Layout Engine for iOS, with support for blocks - meaning that I want to parse NSStrings and create a block during runtime.
1)这甚至可能吗?如果是这样,怎么办?
1) Is this even possible? If so, how can it be done?
在NSString to Block
上找不到更多内容,我认为原因可能是编译器如何处理块-因此我再次搜索答案,但空手而归.所以:
Not being able to find much on NSString to Block
, I thought that the reason may be how a block is handled by the compiler - so again I searched for an answer but came up empty-handed. So:
2)在Objective-C中编译时一个块会发生什么?
2) What happens to a block at compile time in Objective-C?
推荐答案
块是两件事情.在执行通过块的那一刻捕获的大量可执行代码和状态.
A block is two things; a hunk of executable code and state captured at the moment when execution passes over the block.
即给出:
myBlock = ^{ return someVariable + someOtherVariable; };
编译后,这将创建一段代码,其功能非常类似于将两个变量加在一起的函数,返回结果.没有创建块实例.
When compiled, this creates a chunk of code that acts very much like a function that adds two variables together returns the result. No block instance is created.
在执行时,当对表达式myBlock = ^{...};
求值时,将创建一个块实例.在该块实例内部是对编译器创建的代码的引用,以及对myBlock
进行赋值时两个变量中包含的值的副本(当然,除非
When executing, when the expression myBlock = ^{...};
is evaluated, then a block instance is created. Inside that block instance is a reference to the code the compiler created and a copy of the values contained in the two variables at the time the assignment to myBlock
was made (unless, of course, __block
is in play, etc...).
答案(2),但与答案(1)有关.
That answers (2), but is relevant to answering (1).
在运行时,您可以整天创建现有的,已编译的,阻止的实例.但是,您不能创建新的种类块.这样做需要编译器,并且仅限于运行时环境,在该环境中可以编译新的可执行代码并实际执行它.
At runtime, you can create instances of existing, compiled, blocks all day long. You cannot, however, create new kinds of blocks. Doing so would require a compiler and would be limited to runtime environments where compiling new executable code and actually executing it is possible.
这篇关于一块在编译时会发生什么,我可以在运行时创建一个吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!