Does a property require strong keyword? - ios

Properties are now synthesized by default. The compiler will use the property name plus the underscore prefix to create the ivar. And instance variables have strong storage type by default, so it means property is by default strong. So why does property require a strong keyword (seen a lot many people specify it explicitly). Are there be cases where property is weak? Sorry, if it seems to be a noob question.
Edit: IBOutlet, delegates should be weak, any other property apart from that which should be weak.

Properties are strong and atomic by default.
Typing it in explicitly is more for readability purposes than anything else.
There are times when you should use weak properties. Delegates, IBOutlets, etc...
But you have to declare these explicitly.

I would also add to the other answers that block properties require you to specify ownership explicitly.
Usually you need copy for blocks (strong works correctly under ARC but you must use copy under MRC)

Views and Delegates should almost always be weak.
Views should only have a strong reference from superviews.
Delegates should just have to care that their work was done.

Generally weak references are seen automatically from IBOutlets since the view itself holds a strong reference. There are many other use cases. This is to prevent retention cycles.
http://www.quora.com/What-is-the-difference-between-strong-retain-nonatomic-etc-in-objective-C-iOS-property
Avoiding circular retention using ARC (strong/weak), learning some basics
EDIT:
More information can be found here and should be fully understood before looking specifically for examples of weak references besides IBOutlets and delegates. Understanding why each of those are generally weak references would lead to an explanation of what should or shouldn't be weak.
Differences between strong and weak in Objective-C

Related

Manually set nil to swift object to avoid retain cycle?

I've been profiling one of the apps written in swift lately and been very frustrated with ARC in general, coming from languages where mark-and-sweep GC is the norm.
Especially, UIViewControllers that are very complex with lots of dependencies to other class, I've been failing to get ARC working properly. But I know that simply setting retained objects to nil gets them deallocated without dabbling with ARC.
This is especially true for UIViewController where I can set nil to all retained objects in viewDidDisappear or the similar.
Is this kind of practice considered bad / harmful? Should I just try harder to get ARC working?
edit: By not working, I mostly mean to break Strong Reference Cycle, which becomes quite unwieldy when there are multiple hierarchies of dependencies.
edit: FYI, I'm aware that using weak / unowned in declaration / capture list breaks the retain cycle. I'm asking in cases where using those norms become unwieldy due to the complexity of an object or, rather, the retain cycle of an object.
I think you should take a look at your class structure - basically work out which classes should "own" certain properties (i.e. strong reference) and who just needs to be referencing them when they are available (i.e. weak references).
I think it is well worth thinking about this, as it will probably streamline your code. It will also give you an opportunity to really think about privilege - do all these other classes really need access to these objects etc.
The real problem with setting things to nil is that you have to be sure that you are catching all strong reference cycles and that, ultimately, you are not benefiting from ARC making your life easier.
Try deinit Method its wright way I guess
deinit{
person = nil
}

why it is recommended to use the _weak reference with delegates

Hi every one whether some one will elaborate me that why it is recommended to use the _weak reference for delegates and not the strong reference? though we can also use the strong reference for delegates. Some one will please tell me with the better and descriptive example with simple way that in which situations should we use the strong reference and in which situations should we use the _weak reference for the delegates.
I went through one of the related question on stack overflow
Is it ever Ok to have a 'strong' reference for a delegate?
but it did not clear my concept properly.
Any help will be highly appreciated !!
Thanks.
Using __strong on delegate is very easy to create retain cycle:
say A has a strong reference to B, and some object set A as a delegate of B, if the delegate is strongly referenced, then, a retain cycle is formed.
Yes, It's east to creat a retain cycle while using __strong on delegate.
Addtionally, in ARC, we using weak on delegate,while the object using the delegate is released,the delegate will be nil automatically.

How to know which attributes to use with different properties? [duplicate]

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".

What are the disadvantages of setting every property to strong?

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

Naming convention of instance variables when synthesizing properties

When synthesizing properties in Objective-C, it's recommended that you dont simply write:
#synthesize window;
but rather
#synthesize window = _window;
The reasoning is that you don't want your instance variable named the same as your getter method or "bad things can happen".
I've always used #synthesize var1, var2, etc in my apps without "bad things" happening. What sort of bad things could happen?
Bad things used to happen, particularly in the pre-ARC days when people would assign objects to the storage iVar instead of the property. If this was done by accident, then the memory management implied by the synthesized setter wouldn't be applied, leading to leaks, or premature releases.
I use to do it the simple way, but now I use prefixes. I don't declare my iVar themselves anymore, I let the modern runtime take care of that for me. I use prefixes so that I don't accidentally use an iVar like a local variable.
Also - I tend to refer to my properties as self.iVar almost everywhere in my classes. This is so that I can use lazy loaded properties when I want to without worrying about which ones are and are not lazily loaded.
The biggest reason for using the leading underscore in instance variables (like _myProperty) is that when people read the code with the leading underscore, they know that you are using an instance variable, not a local variable, a global variable, or forgot to write "self." like self.myProperty, and that you did this intentionally.
Before ARC, _myProperty wouldn't do any reference counting, while self.myProperty would (for "retain" / "strong" properties). With ARC when you are using "copy" properties, _myProperty does reference counting but still does no copying, so there is still some difference. The most important difference is that _myProperty won't trigger any observers.

Resources