ios - objective-c using blocks with recursion -


i coding iphone app. , when used blocks recursion in objective-c,
got warning message of

capturing addimagetouploadentity in block lead retain cycle.

i created block called addimagetouploadentity used call async function [self.submissionentity addimagedata: toimagealbumtype: finish^{}] 1 one. when hits base case (index <= 0), reload table view , return.

    __block void (^addimagetouploadentity)(nsuinteger) = ^(nsuinteger index){         if (index <= 0)         {             [self.tableview reloaddata];             return;         }          [self.submissionentity addimagedata:[imagespatharray objectatindex:index] toimagealbumtype:_currentoperatingimagealbumtype finish:^{             // recursively call block index+1             addimagetouploadentity(index-1);         }];     };     addimagetouploadentity(5); 

after have researched bit, suggested call function addimagetouploadentity() weak type inside block. rewrote part , tried. then, got error of 'bad access'.

what should in order improve code? , block, have memory leak risk?

    __block void (^addimagetouploadentity)(nsuinteger);     void (^__block __weak weakaddimagetouploadentity)(nsuinteger);      weakaddimagetouploadentity = addimagetouploadentity = ^(nsuinteger index){         if (index <= 0)         {             [self.tableview reloaddata];             return;         }          [self.submissionentity addimagedata:[imagespatharray objectatindex:index] toimagealbumtype:_currentoperatingimagealbumtype finish:^{             // recursively call block index+1             weakaddimagetouploadentity(index+1);         }];     };     addimagetouploadentity(5); 

the asynchronous completion handler addimagedata:toimagealbumtype:finish: needs capture strong reference block. convert weak reference strong reference, , use strong reference inside of asynchronous completion handler:

typedef void (^addimageblock)(nsuinteger);  __block __weak addimageblock weakaddimage = nil;  addimageblock addimage = ^(nsuinteger index) {     if (index <= 0)     {         [self.tableview reloaddata];         return;     }      addimageblock strongaddimage = weakaddimage;     [self.submissionentity addimagedata:[imagespatharray objectatindex:index] toimagealbumtype:_currentoperatingimagealbumtype finish:^{         // recursively call block index+1         strongaddimage(index+1);     }]; };  weakaddimage = addimage; addimage(5); 

the addimageblock kept alive until last asynchronous method handler executed , released.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -