I am new at objective-c.I have a question .I know little about Retain .All i know is Retaining an object creates a strong reference, and an object cannot be deallocated until all of its strong references are released. If two objects retain each other, neither object ever gets deallocated because the connection between them cannot be broken. In ARC we can not retain a object. But we can retain a property.
What is the difference between retaining a object and retaining a property.
Thank You
Happy coding.
After searching so many articles and links, I decided to put all the attributes information together:
atomic //default
nonatomic
strong=retain //default
weak
retain
assign //default
unsafe_unretained
copy
readonly
readwrite //default
Many thanks to all the people who give best answers here!!
a property is retain, mean the class own the property NSObject, that's nothing about ARC. ARC just do auto release reference count.
Related
When I use
addObserver:forKeyPath:options:context:
In this method, will the observer be a strong reference or just a weak reference in ARC?
Any ideas for this problematic?
See the documentation here
Note: The key-value observing addObserver:forKeyPath:options:context:
method does not maintain strong references to the observing object,
the observed objects, or the context. You should ensure that you
maintain strong references to the observing, and observed, objects,
and the context as necessary.
In short: The method does not maintain a strong reference to the observer.
This question occured to me while reading this.
My question is in reference to the image below:
Once john is set to nil, Person instance no longer has any more strong reference and hence will be deallocated. But Apartment has two strong references and one of which is by the property on Person instance that would be soon deallocated. I believe, this strong reference continue to remain after deallocation and goes out of reach by the code.
So, setting unit14A to nil will remove only one strong reference to Apartment instance and it should not be deallocated as there would be one more strong reference due to the above case.
But, as the document says Apartment instance promptly got deallocated. To me, this can only happen if at the time of Person instance deallocation it sets its apartment property to nil, by that removing that strong reference on Apartment instance. But I couldn't find any documentation to verify this.
So, How does the Apartment instance get deallocated? What happened to the strong reference from the Person instance apartment property?
Can someone help me to understand this?
Objective-C objects are reference counted, meaning that for each object, the system keeps track of how many other objects hold a reference to it. This is object's reference count. Two special messages, retain and release, are used to maintain the reference count behind the scene. Once reference count goes down to zero, the system deallocates the object.
ARC provides "magic" to make reference counting work in a declarative way. The compiler knows every strong reference in your code, so when you do this
myStrongRef = nil;
the compiler quietly inserts a call to release in front of the assignment:
[myStrongRef release];
myStrongRef = nil;
To me [deallocation of Apartment] can only happen if at the time of Person instance deallocation it sets its apartment property to nil, by that removing that strong reference on Apartment instance.
Setting a strong reference to nil one way of breaking a strong reference. It is sufficient, but it isn't necessary. The important thing about setting a strong reference to nil is not the act of setting itself, but what happens immediately before it: the instance referred to by the strong reference gets a release message, instructing it to decrement its reference count. That is precisely what ARC does behind the scene for you: it sends the release message to Apartment, without setting Person's reference to nil.
How does the Apartment instance get deallocated? What happened to the strong reference from the Person instance apartment property?
Once strong reference from Person has sent its release message to Apartment, that strong reference disappears. The actual pointer may be set to Apartment's address, but nobody cares about it, because the Person itself is unreachable.
The life of an object depends on it's reference count, not any actual pointer to the object.
Strong reference is a way of speaking, there is no difference between a strong and weak reference, they are just pointers. The difference is that when a strong reference is created the reference count of the object pointed to in incremented and when deleted the reference count is decreased. When an object's reference count would become zero the object is deallocated.
Your intuition is correct. When an object is being deallocated under ARC all the strong references it holds are first relinquished - essentially they are set to nil, but in practice the implementation may differ.
This is also what happens when a method returns, or a block of code containing declarations exits, all the strong references held in local variables are relinquished.
All the details can be found in the Clang documentation.
HTH
Obviously not before deallocation, but during deallocation.
When an object's reference count goes to zero, the deallocation process starts. The object is marked as "being deallocated". At that point, the object will die (unlike Java, where it can be recovered). If an object is marked like this, it cannot be assigned to weak references (they stay nil), or to strong references.
Then dealloc is called, that is the dealloc methods that you have written. After that, strong references are set to nil, reducing their reference counts, then associated objects are removed, and finally the memory for the object is deleted.
How retain cycle was tackled in NON-ARC !
I know assign is an alternative to weak.
weak will have its value set to nil If object allocated is deallocated whereas assign is not
so how it was done earlier can anybody help me understand
Zeroing weak references (what ARC calls weak) only exist under ARC.
Non-zeroing weak references (what ARC calls unsafe_unretained) can be used in MRC or ARC, and is the only kind of "weak reference" that is used in MRC.
You are asking how to avoid dangling references with non-zeroing weak references. You just have to design the logic of the program so that it doesn't happen. It's not that hard.
Usually, a "parent" object will have strong references to "child" objects, and then a back-reference from the "child" object to the "parent" will be a weak reference (in this case a non-zeroing weak reference). All you have to do is, when the "parent" object is deallocated, in its deinitializer, nil out the back-references that the "child" objects have to it -- it can access these "child" objects since it has a reference to them.
Can someone explain to me in detail when I must use each attribute: nonatomic, copy, strong, weak, and so on, for a declared property, and explain what each does? Some sort of example would be great also. I am using ARC.
Nonatomic
Nonatomic will not generate threadsafe routines thru #synthesize accessors. atomic will generate threadsafe accessors so atomic variables are threadsafe (can be accessed from multiple threads without botching of data)
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.
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...)
Retain
retain is required when the attribute is a pointer to a reference counted object that was allocated on the heap. Allocation should look something like:
NSObject* obj = [[NSObject alloc] init]; // ref counted var
The setter generated by #synthesize will add a reference count to the object when it is copied so the underlying object is not autodestroyed if the original copy goes out of scope.
You will need to release the object when you are finished with it. #propertys using retain will increase the reference count and occupy memory in the autorelease pool.
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.
This is a good website to learn about strong and weak for iOS 5.
http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1
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.
nonatomic property means #synthesized methods are not going to be generated threadsafe -- but this is much faster than the atomic property since extra checks are eliminated.
strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.
weak ownership means that you don't own it and it just keeps track of the object till the object it was assigned to stays , as soon as the second object is released it loses is value. For eg. obj.a=objectB; is used and a has weak property , than its value will only be valid till objectB remains in memory.
copy property is very well explained here
strong,weak,retain,copy,assign are mutually exclusive so you can't use them on one single object... read the "Declared Properties " section
hoping this helps you out a bit...
This link has the break down
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.spelling.property
assign implies __unsafe_unretained ownership.
copy implies __strong ownership, as well as the usual behavior of copy
semantics on the setter.
retain implies __strong ownership.
strong implies __strong ownership.
unsafe_unretained implies __unsafe_unretained ownership.
weak implies __weak ownership.
Great answers!
One thing that I would like to clarify deeper is nonatomic/atomic.
The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents.
I.e. atomic will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute.
For example:
#interface MyClass: NSObject
#property (atomic, strong) NSDictionary *dict;
...
In this case it is guaranteed that the pointer to the dict will be read/set in the atomic manner by different threads.
BUT the dict itself (the dictionary dict pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.
If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare).
If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one.
It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".
As a new iOS programmer, I've had a slew of bugs to fix today, a few of them have been related to me using weak properties instead of strong.
I realise that a good programmer wouldn't have this problem and would only set the properties to strong that need to be, but nonetheless, in my newbie eyes, I can't see why I should use weak, it only adds the risk of problems.
In general, you should decide between weak, strong, assign, and copy by looking at the relationship between the class holding the property and the value of that property, and also the kind of the property being passed.
If the property being set is primitive, use assign (or do not use ownership qualifier at all)
If the property being set is a scalar, immutable object, use strong
If the property being set is a scalar, mutable object implementing NSCopying protocol, use copy
If the property being set is mutable, and the ownership is transferred to your object, use strong
If the property being set is a mutable object implementing NSCopying protocol, but the ownership remains with the caller, use copy
If the property being set is a back reference (i.e. a "to parent" property in a "child" object), use weak.
The concept of ownership is very important in reference counted memory models. This is the primary driving factor behind your decision. You need to decide where is the primary owner of an object, and give that owner a strong reference. If an ownership is shared among a group of objects, give them all a strong reference.
The most difficult situation is when objects could own each other, directly or indirectly. In this case you would be better off replacing "ownership" with "knows about", give all objects a common "top" owner who "owns" everybody, and model the "knows about" relationships with weak references.
weak and strong are very important to get right for memory management purposes.
strong will increase the reference counter for the pointer, and you effectively say that you own the object.
weak does not increase the reference counter, and the object can potentially disappear at any time. If you have a cyclic dependency, you should use weak to avoid a memory leak (two objects both having a strong reference to each other is a cyclic dependency and those objects will never be released).
You should always think about your memory management, but a good rule of thumb is that the property should always be strong, unless you positively know that it is retained elsewhere. Multiple objects can have a strong reference to the same object with no problems, as long as no cyclic references occur.
Some super basic rules of thumb:
If you want the object to stick around at least until you are finished with it, go with strong
If you can handle the object disappearing without it hurting you too bad (i.e it is the parent that created you that might be nice to know about but not super important) then use weak
if it is not an NSObject (so is an int, bool float or other primitive type) use assign.
A rule of thumb that I use is: if the object is retained somewhere else, use weak. The biggest thing for me is when using interface builder. If you have an IBOutlet, you can make it weak, because that object is taken care of in interface builder and in the XIB file