• Block系列2:Block内存管理


    ViewController.h

    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController
    {
        UIImage *_image;
        NSInteger _index;
    }
    
    
    @end
    ViewController.m
    #import "ViewController.h"
    #import "Person.h"
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        
    //规则1-- block调用Object-C的对象,对象会被retain
    
        UIButton *button = [[UIButton alloc]init]; //retainCount 1
        //使用__block修饰,引用计数不会加1
        __block UIButton *btn2 = [[UIButton alloc]init]; //retainCount 1
        
    //规则2-- block调用基本数据类型。那么基本数据类型被看成是常量
        int number = 10;
        __block int num = 20;
      
    //规则3-- block引用实例变量(全局变量或者能够觉得是属性)。该实例所在的对象会被retain
         _image = [[UIImage alloc]init];
        _index = 30;
    //声明加实现
        void (^myBlock)(int) = ^(int a){
            
            //对象
            NSLog(@"button的地址:%p",button); //retainCount 2
            NSLog(@"btn2的地址:%p",btn2); //retainCount 1
           
            //基本数据类型
            //错误,常量不能被再次赋值
            //        number = 20;
            num = 10;
            NSLog(@"num:%d",num+a);
            //这种方法不准确。不建议使用 (required)
    //        Do not use this method. (required)
    //        NSLog(@"%d",button.retainCount);
            
            //实例变量【属性】
    //        block引用image,image所属的对象self【ViewController】会被retain
             NSLog(@"_image的地址:%p",_image);
      
        };
        myBlock(10);
        [button release];
        [btn2 release];
        
        Person *person = [[Person alloc]init];
        //实现block
        [person testBlock:^(int a) {
            //_index为全局变量
            //block引用_index,_index所属的对象self【ViewController】会被retain
            NSLog(@"a+_index = %d",a+_index);
        }];
       
       
        
    }
    
    person.h

    #import <Foundation/Foundation.h>
    
    typedef void(^PersonBlock) (int a);
    
    @interface Person : NSObject
    //声明block
    -(void)testBlock:(PersonBlock )block;
    
    @end
    person.m

    #import "Person.h"
    
    @implementation Person
    //调用block
    -(void)testBlock:(PersonBlock )block
    {
        block(10);
    }





  • 相关阅读:
    Silverlight 3中param参数列表汇总
    在Silverlight中使用SmoothStreamingMediaElement创建Smooth Streaming播放器
    动态指定任意类型的ObjectDataSource对象的查询参数
    JQuery Ajax通过Handler访问外部XML数据
    在Excel中输入特殊字符
    SQL Server 2008禁止修改表结构的解决办法
    在xslt中实现split方法对查询字符串进行分隔
    xslt中的foreach排序
    在页面上传递参数给Silverlight插件
    [轉]Log Explorer for SQL Server 4.2
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/6791781.html
Copyright © 2020-2023  润新知