Daoxin
Daoxin

Reputation: 41

Is there any way to check local variable referenced from block is retained?

Apple doc says "In a manually reference-counted environment, local variables used within the block are retained when the block is copied. Use of instance variables within the block will cause the object itself to be retained. "

I was going to check local variable is retained by block or not using retainCount, but failed. Can anyone help me?

Upvotes: 2

Views: 187

Answers (2)

bbum
bbum

Reputation: 162722

A block won't retain an object unless the block is copied. Since a block can only capture state within the same scope as that captured state, the implementation assumes no need to actually retain anything unless the block is copied for the purposes of escaping the scope of declaration.


Think of it in terms of "execution pointer" (kinda like when you are stepping through code in the debugger).

When the execution pointer passes over a block's declaration, that block captures a snapshot -- copies -- all variables that are used within the block's scope that are not declared within the block itself. For an object, that means the block makes a copy of the reference to the object, not a copy of the object itself.

A block starts on the stack. When a block is copied the first time, it is copied from the stack to the heap using a compiler generated per-block "copy helper" (a simple block may not have a copy helper and might actually never be on the stack). That copy helper will retain any objects referenced by the block (that are not referenced via an __block variable anyway).

They won't be released until the block is released and deallocated.

Upvotes: 1

justin
justin

Reputation: 104698

retainCount is useless.

trust the documentation for the implementation. if that fails or defies your expectation for some reason, provide a sample program.

there's no need to verify the retain count, because that's how it works.

if you do doubt it and want to sanity check it, Instruments can be configured to record reference count operations of NSObjects. in that case, run as usual (launched from Instruments, of course), locate the instances of interest in the list of allocated objects, then evaluate the backtraces of the ref-count-ops of the objects of interest. you should see it in there.

Upvotes: 0

Related Questions