Dealing with async calls and block.

Hi All

There are always disadvantages of retaining “self” in side block we can work around it using __block or __weak ref of self. but the ideal way is as we call it strong weak dance. it goes like this

__weak typeOf(self)ref=self;  //making weak ref of self

^( ){
__strong typeOf(ref)strongSelf=ref;   // converting it back to strong
if(!strongSelf)return;   // safety valve in case the thing is being called in async mode to prevent bad access.
[strongSelf->instanceVariable   <call method>];

};

But always writing this was a little tire some for me so i did a macro. It goes like this.

//Macro Mania for repetetive block strong weak ref

#define  _WEAKREF(obj)              __weak typeof(obj)ref=obj;
#define  _STRONGREF(name)      __strong typeof(ref)name=ref;
if(!name)return ;

Define it in your header file or any where you like.

Now you can do this where your macro is visible.

_WEAKREF(self);  //making weak ref of self
^( ){
_STRONGREF(strongSelf)                     // converting it back to strong
// safety valve in case the thing is being called in async mode to prevent bad access.
[strongSelf->instanceVariable   <call method>];

};

now you can safely submit this block to any async task..

 

A pat on the back !!