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);
}





posted @ 2017-07-25 14:37  lytwajue  阅读(154)  评论(0编辑  收藏  举报