enigma enigma - 1 year ago 94
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 Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download