问题描述
这是一个两部分的问题,希望我能够更深入地了解这个主题。
1)在我看来,在目标c
中,有两个选项用于声明类的属性。一个是将属性添加到标题的类体例如。
@interface MyClass:NSObject {
NSArray * myArray ;
}
也可以在 @interface
正文和 @end
语句之前。
@interface MyClass:NSObject {
//
}
@property(nonatomic,retain)NSArray * myArray;
这两种样式有什么区别,以及何时选择 @property
之后,您可以找到之类的选项>(nonatomic,retain)
。
这里是唯一的Xcode可识别的属性修饰符:
-
非原子
属性,主要用于整个程序中只使用一个线程时) -
atomic
(默认) -
保留
/strong
(自动保留/释放集合上的值,确保值不会意外释放)(默认值为ARC和对象类型)
-
readonly
(不能设置属性)
-
readwrite
-
assign
/unsafe_unretained
(不使用此属性进行内存管理,手动分配值)(如果不是ARC或对象类型,则为默认值) -
copy
-
weak
(自动将零值设置为零)引用应该释放对象,并且不保留传递的值) -
getter = method
此属性的值) -
setter = method
(设置用于设置此属性值的选择器)
This is a two part question in hopes that I can understand more about the topic.
1) It seems to me that you have two popular options for declaring a property for a class in objective c
. One is to add the property to the header's class body eg.
@interface MyClass : NSObject {
NSArray *myArray;
}
Or you can add it after the @interface
body and before the @end
statement like so.
@interface MyClass : NSObject {
//
}
@property (nonatomic, retain) NSArray *myArray;
What is the difference between these two "styles" and when do you choose one over the other?
2) after the @property
you find options such as (nonatomic, retain)
. What are those for and why/when do you use different options?
解决方案 Here are the only property modifiers that Xcode recognizes:
nonatomic
(does not enforce thread safety on the property, mainly for use when only one thread shall be used throughout a program)atomic
(enforces thread safety on the property, mainly for use when multiple threads shall be used throughout a program) (default)retain
/ strong
(automatically retains / releases values on set, makes sure values do not deallocate unexpectedly) (default if ARC and object type)readonly
(cannot set property)readwrite
(can both set and get property) (default)assign
/ unsafe_unretained
(no memory management shall be done with this property, it is handled manually by the person assigning the value) (default if not ARC or object type)copy
(copies the object before setting it, in cases where the value set must not change due to external factors (strings, arrays, etc).weak
(automatically zeroes the reference should the object be deallocated, and does not retain the value passed in)getter=method
(sets the selector used for getting the value of this property)setter= method
(set the selector used for setting the value of this property)
这篇关于iOS属性声明澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!