enigma enigma - 1 month ago 6
iOS Question

How to call instance methods inside a block?

I want to call instance methods inside a block. Here is the method that I am working with,

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


But I am not able to reference self from inside this block. What should I do?

EDIT: I am sorry that I posted this question in a hurry. Actually I was getting a warning (Capturing 'self' strongly in this block is likely to lead to a retain cycle) with this approach.

Answer

Using self directly inside a block may cause a retain cycle, to avoid a retain cycle you should create a weak reference to self and then use that reference inside the block to call your instance methods. Use the below code to call instance methods inside a block

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