objective c - Call Block_Release inside block to be released -
is possible release block inside itself? compiler it's fine, i'm not sure if @ runtime crash, since releases memory executed @ same time.
cancel_block_t somefunction(/*args*/){ __block bool canceled = no; __block cancel_block_t cancel_block = block_copy(^{ canceled = yes; block_release(cancel_block); //<-- can this? cancel_block = null; //<-- can this? }); // […] return cancel_block; }
would approach more safe?
cancel_block_t somefunction(/*args*/){ __block bool canceled = no; __block cancel_block_t cancel_block = block_copy(^{ canceled = yes; dispatch_async(dispatch_time(dispatch_time_now, 0.001 * nsec_per_sec), dispatch_get_global_queue(dispatch_queue_priority_low, 0),^{ block_release(cancel_block); cancel_block = null; }); }); // […] return cancel_block; }
thanks help!
edit #1: corrected return type of function.
is non-arc code? arc automatically copy, retain, , release blocks.
anyway, not safe, @ least not always. i've seen crashes similar behavior. issue reference __block
variable within same block object block_release()
may deallocate. so, trying set variable can access memory after it's been freed (and maybe reused).
about function:
1) why return pointer block type? more normal function return block type (which reference). is, somefunction()
should have return type of cancel_block_t
, not cancel_block_t*
. anyway, it's not safe take address of __block
variable, since such variable can change location. starts life on stack gets moved heap.
2) normal semantics function returns block return autoreleased object. so, somefunction()
should return [cancel_block autorelease];
(given it's been copied). caller responsible retaining if wants keep beyond current scope or autorelease pool. if it's submitted function (e.g. dispatch_async()
), function responsible retaining it. in other words, memory management semantics same other object. block should not try release itself.
Comments
Post a Comment