assign与weak区别(面试)

 weak 比 assign 多了一个功能就是当属性所指向的对象消失的时候(也就是内存引用计数为0)会自动赋值为 nil ,这样再向 weak 修饰的属性发送消息就不会导致野指针操作crash。

可能不太好理解下面我写了一个演示程序。

OC:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//
// ViewController.m
// weak与assgin的区别
//
// Created by bihongbo on 14/5/20.
// Copyright (c) 2015年 毕洪博. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,weak) id weakPoint;
@property (nonatomic,assign) id assignPoint;
@property (nonatomic,strong) id strongPoint;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.strongPoint = [NSDate date];
NSLog(@"strong属性:%@",self.strongPoint);
self.weakPoint = self.strongPoint;
self.assignPoint = self.strongPoint;
self.strongPoint = nil;
NSLog(@"weak属性:%@",self.weakPoint);
// NSLog(@"assign属性:%@",self.assignPoint);
}
@end

当程序中的注释被打开时,运行程序有可能会崩溃(有时候不崩溃,你可能需要多运行几次),这是因为当 assign 指针所指向的内存被释放(释放并不等于抹除,只是引用计数为0),不会自动赋值 nil ,这样再引用 self.assignPoint 就会导致野指针操作,如果这个操作发生时内存还没有改变内容,依旧可以输出正确的结果,而如果发生时内存内容被改变了,就会crash。

结论:在 ARC 模式下编程时,指针变量一定要用 weak 修饰,只有基本数据类型和结构体需要用 assgin ,例如 delegate ,一定要用 weak修饰。

原文地址:https://www.cnblogs.com/it-k-50/p/5857796.html