码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-07-05 22:25:27      阅读:339      评论:0      收藏:0      [点我收藏+]

标签:

以下内容来自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

 

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

标签:

原文地址:http://www.cnblogs.com/sixindev/p/4623030.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!