RyanSullivan
RyanSullivan

Reputation: 635

Do I need to retain autorelease objects that are referenced in closures?

NSString* myAutoreleasedString = [NSString stringWithString:aString];

[self performFunctionWithAsyncronousCompletion:^(void) {
    NSLog(@"My String is %@, myAutoreleasedString);
}

Is the above code sample memory safe? Will the closure automatically retain and release the reference to myAutoReleasedString or am I supposed to implement this myself?

EDIT

Arc is disabled.

Upvotes: 0

Views: 116

Answers (2)

sfirite
sfirite

Reputation: 161

In non ARC block (Closure) will retain your variables only when "copy" (block will be copied from stack to heap) will be sent to block object. (so if you safe your block to property with modifier copy - everything will be good). Also in your sample - variable will be release correctly after releasing (deallocated block variable).

If not you can get a crash (if your block will be executed when your variable is already deleted). __block modifier doesn't tell compiler to retain object. use __strong instead.

Upvotes: 1

giorashc
giorashc

Reputation: 13713

Yes it is safe as ObjC blocks retains the objects they are referencing. As long as you are not the owner of the string object you do not need to add additional memory management regarding this object.

You can use the __block keyword for explicitly defining variables which will NOT be retained for avoiding reference cycles. (i.e. __block doNotRetainMeInBlock obj = ...)

Upvotes: 0

Related Questions