@throw在块中导致意外泄漏

时间:2016-11-08 03:13:02

标签: objective-c memory-leaks objective-c-blocks

我有以下对象:

typedef void(^Block1)();
typedef void(^Block2)(Block1 block1);

@interface Test : NSObject
@end
@implementation Test
-(void)test:(Block2)block2 {
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    Block1 block1 = ^{
      // intentionally hold a ref of current object
      [self doNothing];
    };

    @try {
      block2(block1);
    } @catch (NSException *exception) {
      // do nothing
    }
  });
}
-(void)doNothing { }
-(void)dealloc{
  NSLog(@"deallocated: %@", self);
}
@end

我使用它如下:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
      Test *t = [[Test alloc] init];
      [t test:^(Block1 block1) {
        // this @throw statement causes leak? 
        @throw [NSException exceptionWithName:@"ERROR" reason:nil userInfo:nil];
      }];
    }
    return 0;
}

如果我从Block2 @throw异常(正如我上面所做的那样),永远不会调用-dealloc方法,如果除了@throwing异常之外我做任何其他事情,一切都按预期工作。

我在代码中做错了什么,或者这是一个错误?

0 个答案:

没有答案