libextobjc 实现的 defer

算法沉思录:分而治之(复用);

分而治之是指把大而复杂的问题分解成若干个简单的小问题,然后逐个解决。这种朴素的思想来源于人们生活与工作的经验,也完全适合于技术领域。 

要崩溃的节奏;

要崩溃的节奏;

Variable Attributes

libextobjc 实现的 defer 并没有基于 Objective-C 的动态特性,甚至也没有调用已有的任何方法,而是使用了 Variable Attributes 这一特性。

同样在 GCC 中也存在用于修饰函数的 Function Attributes

Variable Attributes 其实是 GCC 中用于描述变量的一种修饰符。我们可以使用 __attribute__ 来修饰一些变量来参与静态分析等编译过程;而在 Cocoa Touch 中很多的宏其实都是通过 __attribute__ 来实现的,例如:

#define NS_ROOT_CLASS __attribute__((objc_root_class))

cleanup 就是在这里会使用的变量属性:

The cleanup attribute runs a function when the variable goes out of scope. This attribute can only be applied to auto function scope variables; it may not be applied to parameters or variables with static storage duration. The function must take one parameter, a pointer to a type compatible with the variable. The return value of the function (if any) is ignored.

GCC 文档中对 cleanup 属性的介绍告诉我们,在 cleanup 中必须传入只有一个参数的函数并且这个参数需要与变量的类型兼容

如果上面这句比较绕口的话很难理解,可以通过一个简单的例子理解其使用方法:

void cleanup_block(int *a) {

    printf("%d ", *a);

}

int variable __attribute__((cleanup(cleanup_block))) = 2;


在 variable 这个变量离开作用域之后,就会自动将这个变量的指针传入 cleanup_block 中,调用 cleanup_block 方法来进行『清理』工作。

原文地址:https://www.cnblogs.com/feng9exe/p/10376613.html