码迷,mamicode.com
首页 > 其他好文 > 详细

Block系列2:Block内存管理

时间:2014-10-23 14:26:57      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:object-c   ui高级   block   内存管理   retain   

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





Block系列2:Block内存管理

标签:object-c   ui高级   block   内存管理   retain   

原文地址:http://blog.csdn.net/pengyuan_d/article/details/40395867

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!