How to use properties in Objective-C?

When should I use the nonatomic , retain , readonly and readwrite in Objective-C?

For example:

 @property(nonatomic, retain) NSObject *myObject; 

If I use nonatomic and retain , does this mean that the object will be saved?

+7
source share
3 answers

First, I wanted to give a comment from David Gelhar to the full answer. The atomic and nonatomic modifiers have nothing to do with thread safety. See this question for more details in this space.

Other items you listed can be viewed relatively simply. I will brief them briefly and point to documentation on property modifiers if you want more.

atomic vs nonatomic first of all guarantees that the full values ​​are returned from the synthesized getters and that the full values ​​are written by the synthesized setters.

readwrite vs readonly determines whether the synthesized property has a synthesized accessor or not ( readwrite has an installer and readonly used by default).

assign vs retain vs copy defines how synthesized accessors interact with the Objective-C memory management scheme. assign is the default and simply assigns the variable. retain indicates that the new value should be sent -retain when assigned and the old value -release . copy indicates that the new value should be sent -copy when assigned and the old value -release .

+10
source

If you use nonatomic , reading and writing the property will not be thread safe. At the moment, I do not think that this is what you need to worry about, but non-atomic access can be faster than atomic access, which is why it is used here.

If you use retain , writing to the property will cause the outgoing value to be freed and the incoming value to be saved, maintaining the correct ratio of the number of references to the value.

+2
source

non-tomic In principle, if you speak non-atomically and you generate accessors using @synthesize, then if several threads try to change / read a property at once, a problem may arise. You may receive partially written values ​​or re-issued / saved objects, which can lead to crashes. (This is potentially much faster than an atomic accessory.)

atomic is the default behavior. nonatomic is thread safe. readonly Externally, the property will be read-only.

The readwrite property will have both an accessor and an installer.

Assign (default) . Indicates that the installer is using a simple assignment. Save . Indicates that the save should be called on the object at the destination. This attribute is valid only for Objective-C object types. (You cannot specify persistence for Core Foundation objects)

copy . Indicates that a copy of the object should be used for the assignment. A release message is sent to the previous value. Copy is performed by calling the copy method. This attribute is valid only for object types that must implement the NSCopying protocol.

+1
source

All Articles