gadu
gadu

Reputation: 1826

Is it safe to pass local variables as method parameters inside of a block?

I know blocks in Obj-C allow you to reference local variables, which is nice. But can we safely pass local variables to another method from inside of a block?

I know referencing self can be dangerous from inside blocks, but does this extend to any other variables.

Example:

-(void)methodTakesObject(ObjectA *)object {

    ObjectB *b = object.b;
    __weak MyObject *weakSelf = self;

    [b doInBackground:^(NSArray *results) {
         [weakSelf doSomethingElseWith:results andWith:object andEvenWith:b];
    }
}

There are three "types" of local variables here. the results from the block, the ObjectB created inside the method, and an ObjectA which was passed to the method to start.

Should I be concerned about using any of these variables, and indeed is there any difference/concerns between how these variables are treated from within the block

Upvotes: 0

Views: 365

Answers (2)

sunshinejr
sunshinejr

Reputation: 4854

If you are worried about retain cycle, @ken gave you the perfect answer. As for the concerns about variables:

  1. object is retained from the method that called methodTakesObject: so you don't have to worry about it. (if it isn't nil, tho).
  2. b is also retained by you, the reference count is likely 2 or more, so you also don't have to worry about it.

In other words, you are safe.

Upvotes: 0

Ken Thomases
Ken Thomases

Reputation: 90621

In fact, it makes no difference no matter what variables are involved.

The concern with a retain cycle is if an object holds a strong reference to a block that it isn't expected to release until it is deallocated while the block holds a strong reference to that same object. That's not happening here.

A method called -doInBackground: seems like it will run the block (starting immediately-ish) and then release the block when it finishes. So, there's no prospect of the block being kept around as long as some other object exists, thus there's no prospect of it keeping that other object around forever.

You don't even need to use the weak-self convention to avoid a retain cycle here. You would only use it in the unlikely case that you really want to allow self to sometimes be deallocated before the block calls its method. More likely, you should just use a normal, strong reference to self because it's normal and/or desirable for self to live long enough for the block to execute.

Upvotes: 1

Related Questions