zoukankan      html  css  js  c++  java
  • 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);
    }





  • 相关阅读:
    javascript对象Math和正则对象
    javascript的Date对象
    初识Python与条件判断
    数据降维_矩阵分析笔记
    数据可视化实战:如何给陈奕迅的歌曲做词云展示?
    数据采集实战:如何自动化运营微博?
    MySQL与Python交互
    27_MySQL数字函数(重点)
    26_ mysql数据操作语言:DELETE语句
    25_MySQL 数据操作语言:UPDATE语句
  • 原文地址:https://www.cnblogs.com/lytwajue/p/7233959.html
Copyright © 2011-2022 走看看