iOS中属性 (nonatomic, copy, strong, weak)的使用 By hL

本文深入解析Objective-C中属性使用中的Copy、Retain、Strong、Weak的区别与应用场景,包括如何正确理解这些关键字在不同情况下的作用,以及在实际项目中的应用案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下内容来自Stackflow的详解

1.Nonatomic
nonatomic is used for multi threading purposes. If we have set the nonatomic attribute at the time of declaration, then any other thread wanting access to that object can access it and give results in respect to multi-threading.

2.Copy
copy is required when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.

常用于(block,NSString)

3.Assign
Assign is somewhat the opposite to copy. When calling the getter of an assign property, it returns a reference to the actual data. Typically you use this attribute when you have a property of primitive type (float, int, BOOL...)

常用于简单数据类型(float, int, NSInteger,BOOL,SEL...)


4.Retain
retain is required when the attribute is a pointer to an object. The setter generated by @synthesize will retain (aka add a retain count to) the object. You will need to release the object when you are finished with it. By using retain it will increase the retain count and occupy memory in autorelease pool.


5.Strong
strong is a replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain.

 

Retain与strong是等价的

如 MBProgressHUD.h 中的宏定义

#ifndef MB_STRONG
#if __has_feature(objc_arc)
    #define MB_STRONG strong
#else
    #define MB_STRONG retain
#endif
#endif


6.Weak
weak is similar to strong except that it won't increase the reference count by 1. It does not become an owner of that object but just holds a reference to it. If the object's reference count drops to 0, even though you may still be pointing to it here, it will be deallocated from memory.

The above link contain both Good information regarding Weak and Strong.

From Stackflow

手思中第三方库AMSmoothAlertView中的相关属性写法参考

关于NSString在MRC时代经常用Copy,Retain属性,而Retain==Strong,所以ARC中很多项目申明为

@property (nonatomic,strong)   NSString    *userName;

参考第2条的Copy介绍,使用 Copy更安全

@property (nonatomic,Copy)   NSString    *userName;

 

相关参考

NSString什么时候用copy,什么时候用strong

 

转载于:https://www.cnblogs.com/sixindev/p/4623030.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值