__attribute__((cleanup(...)))
,用于修饰一个变量(对象),在它的作用域结束时可以自动执行一个指定的方法
例如:
基本用法
1:对于Class对象
// 指定一个cleanup方法,注意入参是所修饰变量的地址,类型要一样
// 对于指向objc对象的指针(id *),如果不强制声明__strong默认是__autoreleasing,造成类型不匹配
// 加了个`unused`的attribute用来消除`unused variable`的warning
static void ZZGCleanUp(__strong ZZG **zzg) {
NSLog(@"%@",*zzg);
}
{
// 调用
__strong Sark *sark __attribute__((cleanup(ZZGCleanUp),unused)) = [ZZG new];
}
// 当运行到这个作用域结束时,自动调用ZZGCleanUp
2:对于NSString对象
static void stringCleanUp(__strong NSString **string) {
NSLog(@"%@", *string);
}
{
__strong NSString *string __attribute__((cleanup(stringCleanUp))