Objective C blocks: is there a way to avoid 'self 'being retained?
I discussed this topic with Apple support, and they told me what I had expected: Currently, there is no way that wocould let me tell the block that it shoshould not retain self. however, they offered two ways to work around the problem.
The first wocould be to pass self as an argument to the block rather than a block variable. The API wocould become:
[Self addeventlistenerfortype: added_to_stage
Block: ^ (ID selfreference, spevent * event)
The API wocould thus be responsible for passing in the (non-retained) self. developers wowould still have to be told that they have to use this reference instead of self, but at least it wocould be easy to use.
The other solution that Apple has used in this sort of situation is to provide a separate method from release/dealloc for shutting down the listener. A good example of this is the "invalidate" method of nstdate. it was created because of a memory cycle
Nsunloop and nstimer (by design ).
This is a nice way to do it. But, for the record, aliasingself
With
A__block
Variable will prevent retention as well.
Http://stackoverflow.com/questions/3975675/objective-c-blocks-is-there-a-way-to-avoid-self-being-retained
From the above discussion, I have no way to let the block reference parameters without causing selfretain's method, but I mentioned three methods to implement the solution of referencing parameters in the block without causing self retain:
1. Pass the current object as a block parameter in the form:
[Request getraidersfrompagenum: pagenum finished: ^ (ID target, Id result, serverresponsestate state)
{
[(Raidersviewcontroller *) Target getraidersinfoandshow: State response: Result pagenum: pagenum];
}];
Target is the current object self, which is similar to the call of Delegate. Target (Self) is used as a local variable, so self will not retain2. call a large method to call (release/dealloc), similar to the invalidate method of timer (but I have not figured out how to use this method, so I will not give an example)
3. Use _ block to convert variables in the form:
-(Void) blocktimer
{
_ Block testviewcontroller * blockself = self;
Dispatch_async (dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^ {
Blockself-> _ timer = [nstimer scheduledtimerwithtimeinterval: 1.0
Target: blockself
Selector: @ selector (caculatelefttimefortomorrow)
Userinfo: Nil
Repeats: Yes];
[[Nsunloop currentrunloop] addtimer: blockself-> _ timer formode: nsdefaultrunloopmode];
[[Nsunloop currentrunloop] Run];
});
}
Manually convert self to the _ block type, so that the block is not in the retain self