zoukankan      html  css  js  c++  java
  • 在 ObjectiveC 中对 Block 应用 property 时的注意事项

    应当使用:@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 copy or 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 retain a 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 copy a 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 copy a heap allocated block, it doesn’t copy it again, it just retains it.

    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.


  • 相关阅读:
    第一课时之导读
    python学习之第十六课时--缩进(indentation)
    python学习之第十六课时--函数的作用及定义
    python学习之第十五课时--存址方式及拷贝
    Linux学习之第七课时--链接(link)文件
    Linux学习之第六课时--文件和目录操作管理命令
    Linux学习之第五课时--文本编辑器
    TOJ--1162---dfs(回溯)
    TOJ---3128---bfs(打印路径)
    TOJ---1502---map真强大
  • 原文地址:https://www.cnblogs.com/Proteas/p/2563747.html
Copyright © 2011-2022 走看看