1猿诸、測(cè)試場(chǎng)景:點(diǎn)擊屏幕的時(shí)候給屏幕添加一個(gè)紅色的view
2茫孔、測(cè)試weak
#import "ViewController.h"
@interface ViewController ()
/** 控件使用weak */
@property (nonatomic,weak) UIView *redView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
_redView = redView;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//設(shè)置frame
_redView.frame = CGRectMake(100, 100, 100, 100);
}
@end
- 小結(jié):點(diǎn)擊屏幕可以實(shí)現(xiàn)屏幕上添加一個(gè)紅色的view
#import "ViewController.h"
@interface ViewController ()
/** 控件使用weak */
@property (nonatomic,weak) UIView *redView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
//[self.view addSubview:redView];
_redView = redView;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//設(shè)置frame
_redView.frame = CGRectMake(100, 100, 100, 100);
}
@end
- 小結(jié):當(dāng)注釋[self.view addSubview:redView];代碼后锦聊,由于redView沒(méi)有強(qiáng)應(yīng)用砰诵,所以過(guò)了viewDidLoad方法以后育拨,redView就會(huì)被釋放了格嘁。此時(shí)的_redView也沒(méi)有指向了應(yīng)該是一個(gè)“野指針”,但是程序并不會(huì)崩潰革为。這是因?yàn)閞edView是由于weak修飾的原因(weak:__weak 弱指針扭粱,不會(huì)讓引用計(jì)數(shù)器+1,如果指向的對(duì)象被銷毀篷角,指針會(huì)自動(dòng)情況)
3焊刹、測(cè)試assgin
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,assign) UIView *redView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIView *redView = [[UIView alloc] init];
redView.backgroundColor = [UIColor redColor];
//[self.view addSubview:redView];
_redView = redView;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//設(shè)置frame
_redView.frame = CGRectMake(100, 100, 100, 100);
}
@end
- 小結(jié):當(dāng)點(diǎn)擊屏幕時(shí),程序會(huì)奔潰?叶住E翱椤!
- 奔潰的原因是因?yàn)閞edView現(xiàn)在是使用 assgin 修飾嘉蕾,assgin的特性如下:assgin: __unsafe_unretained修飾贺奠,不會(huì)讓引用計(jì)數(shù)器+1,如果指向的對(duì)象被銷毀了错忱,指針是不會(huì)自動(dòng)清空的儡率。
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者