对手动创建控件时weak&strong的探究

2017-02-15  本文已影响113人  木格措的天空

例子1:

@property (nonatomic,copy)NSString *zzyText;  // 属性

@implementation ZZYView

// 重写Dealloc并打印数据
-(void)dealloc
{
    NSLog(@"%@----%s",self.zzyText,__func__);
}

@end
#import "ViewController.h"
#import "ZZYView.h"

@interface ViewController ()

@property (nonatomic,weak)ZZYView *weakZView;  //弱引用

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _weakZView = [[ZZYView alloc] initWithFrame:self.view.frame];
    NSLog(@"ZZZZZ");
    _weakZView.zzyText = @"例子1_weakZView";
    _weakZView.backgroundColor = [UIColor redColor];
    [self.view addSubview:_weakZView];
}
2017-02-15 13:47:34.513206 yinyong[3233:1042628] (null)-----[ZZYView dealloc]
2017-02-15 13:47:34.513326 yinyong[3233:1042628] ZZZZZ

例子2:

#import "ViewController.h"
#import "ZZYView.h"

@interface ViewController ()

@property (nonatomic,weak)ZZYView *weakZView;  //弱引用

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    ZZYView *zView = [[ZZYView alloc] initWithFrame:self.view.frame];
    zView.zzyText = @"例子2_weakZView";
    zView.backgroundColor = [UIColor redColor];
    _weakZView = zView;
    [self.view addSubview:_weakZView];
}

#pragma mark点击屏幕触发
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.weakZView) {
        [self.weakZView removeFromSuperview];
    }
}

2017-02-15 14:49:41.271127 yinyong[3268:1051053] 例子2_weakZView-----[ZZYView dealloc]

例子3

#import "ViewController.h"
#import "ZZYView.h"

@interface ViewController ()

@property (nonatomic,strong)ZZYView *strongZView;  //弱引用

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    ZZYView *zView = [[ZZYView alloc] initWithFrame:self.view.frame];
    zView.zzyText = @"例子3_strongZView";
    zView.backgroundColor = [UIColor redColor];
    _strongZView = zView;
    [self.view addSubview:_strongZView];

    /*
     也可以简化这么写
     _strongZView = [[ZZYView alloc] initWithFrame:self.view.frame];
     zView.zzyText = @"例子3_strongZView";
     zView.backgroundColor = [UIColor redColor];
     [self.view addSubview:_strongZView];
     */
}

#pragma mark点击屏幕触发
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.strongZView) {
        [self.strongZView removeFromSuperview];
    }
}
2017-02-15 14:49:46.271127 yinyong[3268:1051053] 例子3_weakZView-----[ZZYView dealloc]

因为ViewController被销毁,其属性strongZView也被销毁,strongZView指针指向的对象引用计数为0也会被释放。

由上面三个例子可以得出:如果你想让一个控件的生命周期随着你的控制器被销毁才去释放,那就使用strong;如果你仅仅是想让它在被移除之后就被释放,那就使用weak。具体选择用哪个还要看你的需求。一般情况下如果没有特殊需求我们手动创建控件时用的是strong来声明,其用法要比weak简捷并且更不容易出错。当然上面例子中的控件用懒加载的方式会更好,我的下一篇文章就会谈谈自己对其的理解。

上一篇下一篇

猜你喜欢

热点阅读