This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
#property and retain, assign, copy, nonatomic
Can someone provide me overview on the properties: retain, assign, copy, nonatomic.
I am the new in iPhone development and I don't know how and when to use these
Thanks in advance.
If you use your own getters/setters then these keywords don't have much of a meaning but if you use #property/#synthesize then u need to use the keywords.
Retain: In this case you get and extra object made that is the retain count for that object is increased by 1 for every retain and you need to release it if you are using arc.Retain is used when you don't want the value to be deallocated while it is set on the object.Also retain creates a strong reference,and an object cannot be deallocated until all of its strong references are released.
Copy: Copy is just reverse of retain as it just gives a copy of the object to work on and the actual value changed on copied object wont be reflected back on the real object . One should use a copy accessor when the setter parameter may be mutable but you can't have the internal state of a property changing without warning .
Assign:Assign is generally used for non-object Datatypes.
Non-atomic: Non-atomic offers thread-safety whereas default atomic doesn't but the read/writes of atomic are thread safe it uses an object level lock that ensure serialization of read/writes.Also ,the value returned from the getter or set via the setter is always fully retrieved or set regardless of what other threads are executing concurrently.If you specify strong, copy, or retain and do not specify nonatomic, then in a reference-counted environment, a synthesized get accessor for an object property uses a lock and retains and autoreleases the returned value.
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Weak and strong property setter attributes in Objective-C
I am new to iphone development . Can any one tell me when to use strong and when to use weak reference and also what is the difference between atomic and nonatomic. I went through many links but still I am not clear with it.
I also wanted to know the differnce between retain,copy and assign used prior to ios5.
Any help is appreciated..
Thanks,
Raj
When designing your data you need to understand the concept of ownership. Data owns downwards. Ownership can never go back up your data hierarchy. If A has a pointer to B, and B to C, then C owns A, you have a cyclic reference graph, which results in a memory leak due to A referencing C indirectly and C referencing A. Release A and it doesn't get deleted because C still has a reference, and it won't get deleted unless A does - a catch 22.
To avoid scenarios like this, you use strong pointers to point "down" your data, and use weak pointers for any back references (such as parent pointers for example).
If a property is atomic, it generates a setter that allows it to be set from multiple threads. You cannot have race conditions where one thread changes a property at the same time as another. Nonatomic properties don't have that thread locking system.
Finally, retain properties increase the reference count of an object when you assign them to it by calling [myObject retain] on the object. Copy calls [myObject copy] so the property does not refer to the original, but a copy and assign is just a straight assignment with no reference count adjustment.
So I've been programming on Objective-C for over a year now, and I can't seem to understand the use for properties. I have searched the internet a few times but never really found a good explaniation. I understand how to create them:
#property (something, something) something *variableName;
#syntheize variableName;
But should I make all my instance variables properties. To me, from what I know, it seems like a waste of code. But when I look at code online, sometimes I see like 25 properties in one class. Which I think is a waste. The only time I ever use them is when passing info from a UITableView cell selected to a detail viewController. For that, I use:
#property (copy) NSString *myString;
Can you also explain what: nonatomic, copy, retain, assign, etc. mean.
Thanks
These properties are convenience methods for creating getters and setters.
Atmoic v Nonatomic
Assuming that you are #synthesizing the method implementations, atomic vs. non-atomic changes the generated code. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory.
With atomic, the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.
In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than atomic.
What atomic does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.
Ensuring data integrity -- one of the primary challenges of multi-threaded programming -- is achieved by other means.
Assign, retain, copy
In a nutshell, assign vs retain vs copy determines how the synthesized accessors interact with the Objective-C memory management scheme:
assign is the default and simply performs a variable assignment
retain specifies the new value should be sent -retain on assignment and the old value sent release
copy specifies the new value should be sent -copy on assignment and the old value sent release.
Remember that retain is done on the created object (it increases the reference count) whereas copy creates a new object. The difference, then, is whether you want to add another retain to the object or create an entirely new object.
Properties are a good technique to expose values. You shouldn't expose all instance variables as that would break good OOP encapsulation.
Here is Apple's documentation on the matter.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html
A key point is:
Declared properties address the problems with standard accessor
methods by providing the following features:
The property declaration provides a clear, explicit specification of
how the accessor methods behave.
The compiler can synthesize accessor methods for you, according to
the specification you provide in the declaration. This means you have
less code to write and maintain.
Properties are represented syntactically as identifiers and are
scoped, so the compiler can detect use of undeclared properties.
Properties enable automatic handling of the variables. So when you do a synthesize the compiler will generate your getters and setters allowing one to do class.variableName = value (indicating that the compiler will execute [class variableName:value].
Pretty decent explanation of the properties here: http://cocoacast.com/?q=node/103
If you need getters and setters to expose some instance variables, or you want some automatic retain/release memory management or thread safe accessors, then properties are a less verbose way to automatically create these smart getters and setters. If you don't want to expose something outside an object or thread, and don't want runtime memory management (say, for some malloc'd C struct) then properties might either a waste, or syntactic sugar (which may or may not improve code readability), or put there by a coder who doesn't know the difference.
The properties is a nice feature which gives you getter and setter method automatically by synthesize and give you relief by not setting and getting the value.
A property may be declared as "readonly", and may be provided with storage semantics such as "assign", "copy" or "retain". By default, properties are considered atomic, which results in a lock preventing multiple threads from accessing them at the same time. A property can be declared as "nonatomic", which removes this lock (reference from http://en.wikipedia.org/wiki/Objective-C#Properties).
When should I use the nonatomic, retain, readonly and readwrite properties in Objective-C?
For example:
#property(nonatomic, retain) NSObject *myObject;
If I use nonatomic and retain, does this mean that the object will be retained?
First off, I wanted to promote the comment from David Gelhar to a full answer. The modifiers atomic and nonatomic have nothing to do with thread safety. See this question for more detail in that space.
The other items you listed can be addressed relatively simply. I'll hit them briefly and point you toward the documentation on property modifiers if you want more.
atomic vs nonatomic primarily ensures that complete values are returned from synthesized getters and that complete values are written by synthesized setters.
readwrite vs readonly determines whether a synthesized property has a synthesized accessor or not (readwrite has a setter and is the default, readonly does not).
assign vs retain vs copy determines how the synthesized accessors interact with the Objective-C memory management scheme. assign is the default and simply performs a variable assignment. retain specifies the new value should be sent -retain on assignment and the old value sent -release. copy specifies the new value should be sent -copy on assignment and the old value sent -release.
If you use nonatomic, reading and writing the property will not be threadsafe. At this point I don't think it is something you need to worry about, but nonatomic 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 released and the incoming value retained, maintaining proper reference-count based ownership of the value.
nontomic Basically, if you say nonatomic, and you generate the accessors using #synthesize, then if multiple threads try to change/read the property at once, badness can happen. You can get partially-written values or over-released/retained objects, which can easily lead to crashes. (This is potentially a lot faster than an atomic accessor, though.)
atomic is the default behavior. nonatomic is thread safe.
readonly Externally the property will be readonly.
readwrite property will have both the accessor, and the setter.
assign (default) — Specifies that the setter uses simple assignment.
retain — Specifies that retain should be invoked on the object upon assignment. This attribute is valid only for Objective-C object types. (You cannot specify retain for Core Foundation objects)
copy — Specifies that a copy of the object should be used for assignment. The previous value is sent a release message. The copy is made by invoking the copy method. This attribute is valid only for object types, which must implement the NSCopying protocol.
In my code, every time I need a new object attribute for my class, I typically copy/paste its name in 4 different places!
The declaration in the header file (NSObject * myObject;)
The #property() line
The #synthesize() line in the implementation
Releasing it under dealloc: (only for objects of course)
I do this because it works, not because I completely understand what's going on. I do know that the declaration in the header file allows other classes to see its attributes, the property specifier determines how its getter/setter methods will be constructed. And the synthesize line actually builds those getter/setter methods. I also know that primitive types should use (nonatomic,assign) instead of (nonatomic,retain), but I have no clue when I should omit the nonatomic.
What can I do to avoid redundancy in my code. If I change or add a variable in my class I have to check 4 different places, and it gets old really fast. Are there any key strokes to make this process faster? Are there lines of code I can simplify or combine to obtain the same result?
Accessorizer will automate a lot of this for you.
In the latest version of Clang (Ships with XCode 4, not in XCode 3 yet) you get default #synthesize as well as default ivar creation. The default ivar creation already works, but not on the simulator. With both of these features all you need to do is add the #property line and deal with the memory management in dealloc
As far as nonatomic vs atomic. atomic is the default, and what happens when you leave off the nonatomic annotation. Atomic guarantees that the value is completely set before allowing anything to access it, nonatomic doesn't. Atomic is only useful in threading situations, and is slightly slower in singlethreaded applications.
It's important to understand what each of those lines of code does. They are not all the same and they are not necessarily redundant. One thing that will help is to use the correct terminology — for example, with NSObject *myObject; you're probably referring to an instance variable declaration.
First and foremost, a #property declaration in an #interface lets you say that instances of a class expose a piece of state. It doesn't say much about the implementation of that state, only that it's exposed by instances of your class and the API contract (memory management, atomicity, methods) for the state.
The #synthesize directive tells the compiler to create or use a specific instance variable as storage for a declared #property. This does not need to be how you provide storage for a property. For example, Core Data provides its own storage for modeled properties, so you use #dynamic for those instead. You also don't need to use an instance variable with the same name as your #property — to extend your example above, you might name your instance variable myObject_ while naming your property object and that's perfectly fine.
Finally, you send the instance variable -release in -dealloc — for an object-type property marked retain or copy — because you've said you'll manage its memory. You're not releasing the property, you're releasing the storage. If you implemented the storage some other way, you'd clean it up some other way.
I'm diving into iOS development and I find that for each of my UI controls, I always just blindly declare their #property like so, since that's how it was done in some tutorial I read when I started learning...
#property (retain, nonatomic) IBOutlet UILabel *lblStatus;
I'm still getting familiar with these attribute types and what they mean, but I find these two attributes allow me to accomplish my goals. Would I ever want to use any #property attributes other than "retain" and "nonatomic" for UI variables?
Thanks in advance for all your help!
NOTE: This answer is more relevant to UI Items in general.
Yes there is other situation where you would want to use the "assign" macro instead of "retain" (Assign is default for now but you get warning at compile-time if you don't specify it explicitly)
Apple gives a good example of this on one of their tutorial: Advanced UITableViewCell
They only "assign" in order to avoid cycle retains. (each of the view retains the other so they can't be deallocated).
NOTE: I missed the reference to UI variables in the question, so this answer is a more general discussion.
Yes, you will definitely need to use other attributes than those two, although that combination is the most common one.
copy - Use this in situations where you don't want as subsequent change to the data to be "picked up" by your class. In other words, when you want full control of the data once it's passed in. Sometimes this is desirable, sometimes not. Classes like NSString and UIColor are often used through properties with the copy attribute. My answer here gives a little bit more background.
assign - You use this with primitive types like int. You can't retain or copy an int or a float, because they are not objects, so you have to use assign. (Also, you don't have to, and can't, release those variables in your dealloc method.) This is true also for C structs, which are not covered by the Objective-C retain count system.
assign special case - sometimes you use assign even with objects, because you want to avoid retain cycles. Look at the header for UITableViewfor example. You'll notice that the delegate property is declared like this: #property(nonatomic, assign) id<UITableViewDelegate> delegate . Delegate properties should always be declared with assign and the same applies in some other situations, although you are not likely to run into them very soon.
nonatomic - This tells the compiler that the property is intended only to be accessed from one thread, and therefore it can omit some code that would otherwise slow down your program (potentially considerably). So the rule here is: if the property will, or might, be accessed from several threads, you should not declare it to be nonatomic (atomic is the default). Note however that making properties atomic is in no way sufficient to make your code thread safe. That's another, and much much thornier, topic.
The answer is NO. The reason behind this is the reason why we are using nonatomic and retain. From memory management guide "Objects in the nib file are created with a retain count of 1 and then autoreleased. As it rebuilds the object hierarchy, UIKit reestablishes connections between the objects using setValue:forKey:, which uses the available setter method or retains the object by default if no setter method is available. This means that (assuming you follow the pattern shown in “Outlets”) any object for which you have an outlet remains valid." So we are providing this setter just to make a match with the default behavior. Yes, it is possible to declare the setter in other ways but at least I have not found no reason to do so. If we use assign instead of retain, then there is no guarantee that the objects will remain valid. And memory management is already critical in iPhone and obviously I don't want to make it further critical by ignoring the convention. -- edit The answer NO is only for UI variables, that is for IBOutlets. Don't be confused. Other attributes are necessary in other cases as explained in other answers.
(retain) is generally used for instance variables and assign will go for delegates and primitive data types like bool , int