【问题标题】:How to call instance methods inside a block?如何在块内调用实例方法?
【发布时间】:2015-06-03 05:39:12
【问题描述】:

我想在一个块中调用实例方法。这是我正在使用的方法,

[self.someVariable addBoundaryTimeObserverForTimes:timeArray queue:NULL usingBlock:^{
    [self myInstanceMethod];
}];

但我无法从该块内引用 self。我该怎么办?

编辑:很抱歉我匆忙发布了这个问题。实际上,我使用这种方法收到了一个警告在此块中强烈捕获“自我”可能会导致保留周期)。

【问题讨论】:

  • 你得到什么错误信息?

标签: ios objective-c-blocks


【解决方案1】:

在块内直接使用self 可能会导致保留循环,为避免保留循环,您应该创建对 self 的弱引用,然后在块内使用该引用来调用您的实例方法。使用下面的代码调用块内的实例方法

__weak YourViewController * weakSelf = self;
[self.someVariable addBoundaryTimeObserverForTimes:timeArray queue:NULL usingBlock:^{
    [weakSelf myInstanceMethod];
}];

【讨论】:

    【解决方案2】:

    试试这个代码:

    __block YourViewController *blockSafeSelf = self;    
    [self.someVariable addBoundaryTimeObserverForTimes:timeArray queue:NULL usingBlock:^{
        [blockSafeSelf myInstanceMethod];
    }];
    

    _block 会保留 self,所以你也可以使用 _weak 引用:

    YourViewController * __weak weakSelf = self;
     [self.someVariable addBoundaryTimeObserverForTimes:timeArray queue:NULL usingBlock:^{
            [weakSelf myInstanceMethod];
        }];
    

    【讨论】:

      【解决方案3】:

      如果你想在一个块中调用实例方法。 你可以试试下面的代码,它是苹果建议的 这是https://developer.apple.com/library/mac/referencelibrary/GettingStarted/RoadMapOSX/books/AcquireBasicProgrammingSkills/AcquireBasicSkills/AcquireBasicSkills.html的链接

      __block typeof(self) tmpSelf = self;
      [self.someVariable addBoundaryTimeObserverForTimes:timeArray queue:NULL usingBlock:^{
          [tmpSelf myInstanceMethod];
      }];
      
      For example
      //References to self in blocks
      
      __block typeof(self) tmpSelf = self;
      [self methodThatTakesABlock:^ {
          [tmpSelf doSomething];
      }];

      【讨论】:

        【解决方案4】:

        是的,你可以这样做。

        __block YourViewController *blockInstance = self;  
        [self.someVariable addBoundaryTimeObserverForTimes:timeArray queue:NULL usingBlock:^{
            [blockInstance myInstanceMethod];
        }];
        

        注意:但是,该块将保留自我。如果最终将此块存储在 ivar 中,则可以轻松创建保留循环,这意味着两者都不会被释放。

        为避免此问题,最佳做法是捕获对 self 的弱引用,如下所示:

        __weak YourViewController *weakSelf = self;
        [self.someVariable addBoundaryTimeObserverForTimes:timeArray queue:NULL usingBlock:^{
            [weakSelf myInstanceMethod];
        }];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-11-21
          • 2016-08-30
          • 2020-01-19
          • 2014-08-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多