objective c - Using method with self inside blocks -
objective c - Using method with self inside blocks -
i need execute same bunch of code in 2 blocks (i'm using arc):
__weak typeof(self) weakself = self; [_dataprovider doa:^(nserror *error) { [weakself handleerror:error]; }];
and in different place call:
__weak typeof(self) weakself = self; [_dataprovider dob:^(nserror *error) { [weakself handleerror:error]; }];
then have handler:
- (void)handleerror:(nserror *)error { [self.refreshcontrol endrefreshing]; [self.tableview reloaddata]; }
is save utilize way? please notice handleerror:
method uses self
inside. if not, proper approach here? btw: self viewcontroller , can dealloced (dob: , doa: blocks based on networking, can slow).
it not safe this, if many people doing this.
you should utilize "weakself" pattern blocks when justified. in illustration "weakself" pattern not justified, because self
don't have strong
reference block
. can utilize :
[_dataprovider doa:^(nserror *error) { // here can utilize self, because don't have strong reference block [weakself handleerror:error]; }];
use "weakself" pattern if have strong
reference block
( property or instance variable example) , capturing self
within block
, illustration :
@property(strong) void(^)(void) completionblock; .... __weak typeof(self) weakself = self; self.completionblock = ^{ // don't utilize "self" here, captured block , retain cycle created // if utilize "weakself" here many times, risques nil @ end of block // should create othere strong reference "weakself" __strong typeof(self) strongself = weakself; // here utilize strongself ( , not "weakself" , not "self") };
objective-c block retain-cycle
Comments
Post a Comment