namespace ocutil {
    class AutoreleasePoolCaller {
    public:
        AutoreleasePoolCaller():pool([[NSAutoreleasePool alloc]init]) {
        }
        ~AutoreleasePoolCaller() {
            [pool drain];
        }
    private:
        NSAutoreleasePool *pool;
    };
}

 

在需要使用AutoreleasePool的Block里声明一个自动变量

{
    ocutil::AutoreleasePoolCaller autoreleasePool;
    // here is your code.
}

这样只要跳出Block,析构函数就会自动呼叫[pool drain],当程序流程变得很复杂,实在忍无可忍想要在某个深层嵌套中goto或者return的时候,就不怕忘记写[pool drain]了;

很怀念这个小把戏,当年刚工作时,传授我这个小把戏的人用它来实现mutex锁的自动lock和unlock。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-24
  • 2022-12-23
  • 2021-05-07
  • 2022-03-09
  • 2021-05-26
  • 2021-08-01
猜你喜欢
  • 2021-11-28
  • 2022-12-23
  • 2022-12-23
  • 2021-07-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案