在 Objective-C 中对 Block 应用 property 时的注意事项
2012-06-26 15:13
423 查看
应当使用:@property (nonatomic, copy)
今天在这个问题上犯错误了,找了好久才知道原因。
另外,简单的进行反汇编看了下,Block 被存储在静态变量区,运行时构造出一个运行栈,进行调用。
retain 并不会改变 Block 的引用计数,因此对 Block 应用 retain 相当于 assign。
但是既然在静态存储区,为什么会出现 EXC_BAD_ACCESS 呢?代码都在的呀。
网上都说 Block 在栈上,这应该是错误的:指向 Block 代码的指针在栈上。
我感觉原因是这样:
执行静态区的代码,需要特殊的构造,比如:加载到寄存器,调整好 ESP 等。
而堆上的代码可以直接执行。
期待更详细的解释。
When storing blocks in properties, arrays or other data structures, there’s an important difference between using
When blocks are first created, they are allocated on the stack. If the block is called when that stack frame has disappeared, it can have disastrous consequences, usually a EXC_BAD_ACCESS or something plain weird.
If you
So you should always declare your blocks as properties like this:
今天在这个问题上犯错误了,找了好久才知道原因。
另外,简单的进行反汇编看了下,Block 被存储在静态变量区,运行时构造出一个运行栈,进行调用。
retain 并不会改变 Block 的引用计数,因此对 Block 应用 retain 相当于 assign。
但是既然在静态存储区,为什么会出现 EXC_BAD_ACCESS 呢?代码都在的呀。
网上都说 Block 在栈上,这应该是错误的:指向 Block 代码的指针在栈上。
我感觉原因是这样:
执行静态区的代码,需要特殊的构造,比如:加载到寄存器,调整好 ESP 等。
而堆上的代码可以直接执行。
期待更详细的解释。
When storing blocks in properties, arrays or other data structures, there’s an important difference between using
copyor
retain. And in short, you should always use
copy.
When blocks are first created, they are allocated on the stack. If the block is called when that stack frame has disappeared, it can have disastrous consequences, usually a EXC_BAD_ACCESS or something plain weird.
If you
retaina stack allocated block (as they all start out being), nothing happens. It continues to be stack allocated and will crash your app when called. However, if you
copya stack allocated block, it will copy it to the heap, retaining references to local and instance variables used in the block, and calling it will behave as expected. However, if you
copya heap allocated block, it doesn’t copy it again, it just
retainsit.
So you should always declare your blocks as properties like this:
@property (copy, ...) (int)(^aBlock)();And never like this:
@property (retain, ...) (int)(^aBlock)();And when providing blocks to
NSMutableArrays and the like, always
copy, never
retain.
相关文章推荐
- 在 Objective-C 中对 Block 应用 property 时的注意事项
- block 应用及注意事项
- Block的基本使用、typedef给Block定义别名、Block的应用场景、Block的注意事项
- android studio设置应用图标时注意事项
- iOS应用内购常见问题及注意事项
- objective-c 分类注意事项
- 使用block应该注意的事项
- img标签的onerror事件(应用以及注意事项)
- 论YH-MC004智能控制系统中的弱电调光优势以应用上的注意事项
- 总结在Google Play成功发行应用的注意事项
- 关于block使用的5点注意事项
- 应用级app覆盖系统级app注意事项
- ViewState的原理,应用场合,注意事项
- caffe2 在树莓派raspberry Pi 3b平台应用(一 源码编译注意事项)
- LoadRunner特殊函数应用注意事项
- FLEX RSL 应用注意事项
- Android Market google play store帐号注册方法流程 及发布应用注意事项
- 使用.net框架应用C#语言开发窗口程序的一些注意事项
- 使用Block 注意事项
- 特殊函数应用注意事项