//参考链接:
assign 直接复制,set方法中没有retain操作,引用计数不会加1。 如果用来修饰对象属性 , 那么当对象被销毁后指针是不会指向 nil 的 . 所以会出现野指针错误 . ( 与weak的区别 )
weak是弱引用,用weak描述修饰或者所引用对象的计数器不会加一,并且会在引用的对象被释放的时候自动被设置为nil,大大避免了野指针访问坏内存引起崩溃的情况,另外weak还可以用于解决循环引用。
strong强引用 修饰的对象引用计数会加一
copy 浅拷贝(指针拷贝) 深拷贝(值拷贝) 容器类型NSArray/非容器类型NSString
strong VS copy strong: 类似于copy的浅拷贝,也就是指针引用(指针拷贝,多了一个指针指向),copy更加的安全
//crash案例1
@property (nonatomic, copy) NSMutableString *strCopy;
self.strCopy = [NSMutableString stringWithFormat:@"abc"];
[self.strCopy appendString:@"def"]; // copy修饰在这一行会crash 因为copy是复制出一个不可变的对象,在不可变对象上运行可变对象的方法,就会找不到执行方法 因此NSMutableString NSMutableArray,NSMutableDictionary用strong修饰
@property (nonatomic, assign) int number;//基本数据类型
@property (nonatomic, weak) id delegate;
@property (nonatomic, strong) UIView *bgView;//字典数组
@property (nonatomic, strong) NSMutableString *strCopy;//可变类型一定要用strong,用copy会导致crash
@property (nonatomic, copy) NSString *copyedStr;//字符串 为什么不用strong?
@property (nonatomic, strong) NSString *strongStr;//字符串
//strong VS copy
- (void)testCopys
{
NSString*string = [NSStringstringWithFormat:@"lalala"];
self.strongStr= string;
self.copyedStr= string;
NSLog(@"origin string: %p, %@", string, string);
NSLog(@"strong string: %p, %@", _strongStr, _strongStr);
NSLog(@"copyed string: %p, %@", _copyedStr, _copyedStr);//&_copyedStr
NSMutableString *mutbleString = [NSMutableString stringWithFormat:@"hahaha"];
self.strongStr= mutbleString;
self.copyedStr= mutbleString;
[mutbleStringappendString:@" wawawa"];
NSLog(@"mut origin string: %p, %@", mutbleString, mutbleString);
NSLog(@"mut strong string: %p, %@", _strongStr, _strongStr);
NSLog(@"mut copyed string: %p, %@", _copyedStr, _copyedStr);
}


https://www.jianshu.com/p/3709cf8f8937
https://www.jianshu.com/p/33f175d97b86
https://www.jianshu.com/p/ddfd5cc0c1b4
网友评论