1、測試場景:點擊屏幕的時候給屏幕添加一個紅色的view
2、測試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é):點擊屏幕可以實現(xiàn)屏幕上添加一個紅色的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沒有強應(yīng)用,所以過了viewDidLoad方法以后,redView就會被釋放了。此時的_redView也沒有指向了應(yīng)該是一個“野指針”,但是程序并不會崩潰。這是因為redView是由于weak修飾的原因(weak:__weak 弱指針,不會讓引用計數(shù)器+1,如果指向的對象被銷毀,指針會自動情況)
3、測試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)點擊屏幕時,程序會奔潰!!!
- 奔潰的原因是因為redView現(xiàn)在是使用 assgin 修飾,assgin的特性如下:assgin: __unsafe_unretained修飾,不會讓引用計數(shù)器+1,如果指向的對象被銷毀了,指針是不會自動清空的。
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。