iOS-assgin與weak的根本區別

本文介紹 iOS 中 assgin 與 weak 的區別

  • 首先是 weak 的使用:一般用于修飾控件:

@interface ViewController ()
@property (nonatomic, weak) UIView *redView;
@end
@implementation ViewController
-(void)viewDidLoad {
    [super viewDidLoad];
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor redColor];
    [self.view addSubview:view];
    self.redView = view;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    _redView.frame = CGRectMake(50, 50, 200, 200);
}

當點擊屏幕的時候走 touchesBegan 方法
redView 有了 frame
會顯示在屏幕上
說明在走完 viewDidLoad 的代碼塊時
redView 沒有被銷毀
因為 redView 被加入了控制器的 view
由控制器對它進行了強引用

-(void)viewDidLoad {
    [super viewDidLoad];
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor redColor];
    //[self.view addSubview:view];
    self.redView = view;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    _redView.frame = CGRectMake(50, 50, 200, 200);
}

現在把這句注掉:[self.view addSubview:view];
繼續點擊屏幕
由于 redView 沒有被加入控制器的view
也就沒有人對它強引用
過了 viewDidLoad 代碼塊后
redView 被銷毀了
但是 touchesBega n中訪問 redView 的時候
程序沒有報壞內存訪問的錯誤

原因就是因為weak做了些事情:

如果指針指向的對象被銷毀,那么 weak 會讓這個指針也清空
這時的 redView 是 __weak 修飾:


weak.jpeg

assgin 的使用:一般用于修飾基本數據類型

為了演示 assgin 與 weak 的區別
用 assgin 來修飾控件

@interface ViewController ()
@property (nonatomic, assign) UIView *redView;
@end
@implementation ViewController
-(void)viewDidLoad {
    [super viewDidLoad];
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor redColor];
    //[self.view addSubview:view];
    self.redView = view;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    _redView.frame = CGRectMake(50, 50, 200, 200);
}

這里用 assgin 修飾的控件 redView 也沒有加入到控制器 view 中
也就沒有人對 redView 進行強引用
當點擊屏幕走 touchesBegan 方法時
就會報壞內存訪問錯誤
因為 assign 并沒有把指針清空
這時的 redView 是 __unsafe_unretained 修飾:


assgin.jpeg

總結:

  • weak:

__weak 修飾
弱指針
不會讓引用計數器 +1
如果指向對象被銷毀,指針會自動清空
ARC才有

  • assgin:

__unsafe_unretained 修飾
不會讓引用計數器 +1
如果指向對象被銷毀,指針不會清空

感謝閱讀
你的支持是我寫作的唯一動力

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容