iOS block 循环引用

 
@interface ToolDemoViewController ()
{
   
BOOL isSuccess;
    void (^testBlock2)(NSString *str);
}
@property ( strong , nonatomic ) NSString           *testName;
@property ( nonatomic , copy ) void (^testBlock)( NSString *str);
 
#pragma mark - 测试循环引用
- ( void )testWeakAction {
   
   
// 这里不需要 __weak
    [
UIView animateWithDuration : 0.3 animations :^{
       
self . view . backgroundColor = [ UIColor redColor ];
       
self . testName = @"sadgf" ;
    }];
   
// 这里不需要 __weak
   
dispatch_async ( dispatch_get_main_queue (), ^{
       
self . view . backgroundColor = [ UIColor blueColor ];
       
self . testName = @"dddd" ;
    });
   
   
// 这里需要 __weak
   
__weak typeof ( self ) wSelf = self ;
   
testBlock2 = ^( NSString *str) {
       
NSLog ( @"===%@" ,wSelf. testName );
    };
   
   
// 测试调用
   
if ( self . testBlock ) {
       
self . testBlock ( @" 测试 " );
    }
   
if ( testBlock2 ) {
       
testBlock2 ( @"ddd" );
    }
 
  void (^testTempBlock) ( NSString * str);
   
// 这里不需要 __weak
    testTempBlock = ^(
NSString *str) {
       
NSLog ( @"%@" , self . testName );
    };
   
// 测试方法里面的 block 的调用
   
if (testTempBlock) {
        testTempBlock(
@"xiao" );
    }

    // block里面有延迟的时候需要特殊处理

    self.testBlock = ^(NSString *str) {

    ToolDemoViewController *strongSelf = wSelf;

      dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

          // 页面返回上个页面后,才执行,就会为空了。。。

          NSLog(@"name111===%@,,,%@",strongSelf.testName,str);

      });

    };

    if (self.testBlock) {

        self.testBlock(@"xiaoming");

    }

}

猜你喜欢

转载自zhangmingwei.iteye.com/blog/2316230