enigma
enigma

Reputation: 876

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.

Upvotes: 0

Views: 623

Answers (4)

Ramkrishna Sharma
Ramkrishna Sharma

Reputation: 7019

Yes you can do this.

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

Note : However, that the block will retain self. If you end up storing this block in an ivar, you could easily create a retain cycle, which means neither would ever get deallocated.

To avoid this problem, it’s best practice to capture a weak reference to self, like this:

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

Upvotes: 0

Vinay Jain
Vinay Jain

Reputation: 1661

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

Upvotes: 2

Abhay Singh Naurang
Abhay Singh Naurang

Reputation: 141

if you want to call instance method inside a block . you could try the below code and it's suggested by apple and here is a link for 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];
}];

Upvotes: 0

Utsav Parikh
Utsav Parikh

Reputation: 1206

Try this code :

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

_block will retain self, so you can also use a _weak reference :

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

Upvotes: 0

Related Questions