如何在块内调用实例方法?

How to call instance methods inside a block?

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

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

但是我无法从这个块中引用自己。我该怎么办?

编辑:很抱歉我匆忙发布了这个问题。实际上我收到了 warning (Capturing 'self' strongly in this block is likely to lead to a retain cycle ) 用这种方法。

试试这个代码:

__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];
    }];

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

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

是的,你可以做到。

__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];
}];

如果您想在块内调用实例方法。 你可以试试下面的代码,这是苹果推荐的 这是 https://developer.apple.com/library/mac/referencelibrary/GettingStarted/RoadMapOSX/books/AcquireBasicProgrammingSkills/AcquireBasicSkills/AcquireBasicSkills.html

的 link

__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];
}];