【问题标题】:call a method in a block?在块中调用方法?
【发布时间】:2012-03-23 07:26:13
【问题描述】:

我是 ARC 的新手。我想在一个完整的块中调用一个方法,但我收到警告:在此块中强烈捕获“自我”可能会导致保留周期。。代码:

- (void) handlerComplete
{
    //...
}

- (void) loadData
{
    ...
    operation.completeBlock = ^(NSInteger index) {
        [self handlerComplete];
    };
}

有什么建议吗?谢谢。

【问题讨论】:

    标签: iphone ios objective-c-blocks


    【解决方案1】:

    试试

    - (void) loadData
    {
        __weak MyClassType *myClass = self;
        operation.completeBlock = ^(NSInteger index) {
            [myClass handlerComplete];
        };
    }
    

    【讨论】:

      【解决方案2】:

      改为使用弱引用:

      operation.completeBlock = ^(NSInteger index) {
          __weak Foo *bar = self;
          [bar handlerComplete];
      };
      

      我认为这会起作用,虽然我还没有验证过。

      【讨论】:

      • 我相信这应该可行,但 __weak(或 __unsafe_unretained)变量可能需要在块外声明。
      • 谢谢,当我将__weak Foo *bar = self; 放入块中时,我得到了同样的警告。当我把它放在街区外时,它就起作用了。
      猜你喜欢
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 1970-01-01
      相关资源
      最近更新 更多