What are the differences between strong and weak in #property declarations of pointers to objects?
Also, what does nonatomic mean?
It may be helpful to think about strong and weak references in terms of balloons.
A balloon will not fly away as long as at least one person is holding on to a string attached to it. The number of people holding strings is the retain count. When no one is holding on to a string, the ballon will fly away (dealloc). Many people can have strings to that same balloon. You can get/set properties and call methods on the referenced object with both strong and weak references.
A strong reference is like holding on to a string to that balloon. As long as you are holding on to a string attached to the balloon, it will not fly away.
A weak reference is like looking at the balloon. You can see it, access it's properties, call it's methods, but you have no string to that balloon. If everyone holding onto the string lets go, the balloon flies away, and you cannot access it anymore.
A strong reference (which you will use in most cases) means that you want to "own" the object you are referencing with this property/variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you point to it with a strong reference. Only once you set the property to nil will the object get destroyed (unless one or more other objects also hold a strong reference to it).
In contrast, with a weak reference you signify that you don't want to have control over the object's lifetime. The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil. The most frequent use cases of weak references in iOS are:
delegate properties, which are often referenced weakly to avoid retain cycles, and
subviews/controls of a view controller's main view because those views are already strongly held by the main view.
atomic vs. nonatomic refers to the thread safety of the getter and setter methods that the compiler synthesizes for the property. atomic (the default) tells the compiler to make the accessor methods thread-safe (by adding a lock before an ivar is accessed) and nonatomic does the opposite. The advantage of nonatomic is slightly higher performance. On iOS, Apple uses nonatomic for almost all their properties so the general advice is for you to do the same.
strong: assigns the incoming value to it, it will retain the incoming value and release the existing value of the instance variable
weak: will assign the incoming value to it without retaining it.
So the basic difference is the retaining of the new variable.
Generaly you want to retain it but there are situations where you don't want to have it otherwise you will get a retain cycle and can not free the memory the objects. Eg. obj1 retains obj2 and obj2 retains obj1. To solve this kind of situation you use weak references.
A dummy answer :-
I think explanation is given in above answer, so i am just gonna tell you where to use STRONG and where to use WEAK :
Use of Weak :-
1. Delegates
2. Outlets
3. Subviews
4. Controls, etc.
Use of Strong :-
Remaining everywhere which is not included in WEAK.
strong and weak, these keywords revolves around Object Ownership in Objective-C
What is object ownership ?
Pointer variables imply ownership of the objects that they point to.
When a method (or function) has a local variable that points to an object, that variable is said to own the object being pointed to.
When an object has an instance variable that points to another object, the object with the pointer is said to own the object being pointed to.
Anytime a pointer variable points to an object, that object has an owner and will stay alive. This is known as a strong reference.
A variable can optionally not take ownership of an object that it points to. A variable that does not take ownership of an object is known as a weak reference.
Have a look for a detailed explanation here Demystifying #property and attributes
Here, Apple Documentation has explained the difference between weak and strong property using various examples :
https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW3
Here, In this blog author has collected all the properties in same place. It will help to compare properties characteristics :
http://rdcworld-iphone.blogspot.in/2012/12/variable-property-attributes-or.html
strong is the default. An object remains “alive” as long as there is a strong pointer to it.
weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.
To understand Strong and Weak reference consider below example, suppose we have method named as displayLocalVariable.
-(void)displayLocalVariable
{
UIView* myView = [[UIView alloc] init];
NSLog(#"myView tag is = %ld", myView.tag);
}
In above method scope of myView variable is limited to displayLocalVariable method, once the method gets finished myView variable which is holding the UIView object will get deallocated from the memory.
Now what if we want to hold the myView variable throughout our view controller's life cycle. For this we can create the property named as usernameView which will have Strong reference to the variable myView(see #property(nonatomic,strong) UIView* usernameView; and self.usernameView = myView; in below code), as below,
#interface LoginViewController ()
#property(nonatomic,strong) UIView* usernameView;
#property(nonatomic,weak) UIView* dummyNameView;
- (void)displayLocalVariable;
#end
#implementation LoginViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
-(void)viewWillAppear:(BOOL)animated
{
[self displayLocalVariable];
}
- (void)displayLocalVariable
{
UIView* myView = [[UIView alloc] init];
NSLog(#"myView tag is = %ld", myView.tag);
self.usernameView = myView;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
Now in above code you can see myView has been assigned to self.usernameView and self.usernameView is having a strong reference(as we declared in interface using #property) to myView. Hence myView will not get deallocated from memory till self.usernameView is alive.
Weak reference
Now consider assigning myName to dummyNameView which is a Weak reference, self.dummyNameView = myView; Unlike Strong reference Weak will hold the myView only till there is Strong reference to myView. See below code to understand Weak reference,
-(void)displayLocalVariable
{
UIView* myView = [[UIView alloc] init];
NSLog(#"myView tag is = %ld", myView.tag);
self.dummyNameView = myView;
}
In above code there is Weak reference to myView(i.e. self.dummyNameView is having Weak reference to myView) but there is no Strong reference to myView, hence self.dummyNameView will not be able to hold the myView value.
Now again consider the below code,
-(void)displayLocalVariable
{
UIView* myView = [[UIView alloc] init];
NSLog(#"myView tag is = %ld", myView.tag);
self.usernameView = myView;
self.dummyNameView = myView;
}
In above code self.usernameView has a Strong reference to myView, hence self.dummyNameView will now have a value of myView even after method ends since myView has a Strong reference associated with it.
Now whenever we make a Strong reference to a variable it's retain count get increased by one and the variable will not get deallocated till it's retain count reaches to 0.
Hope this helps.
Strong: Basically Used With Properties we used to get or send data from/into another classes.
Weak: Usually all outlets, connections are of Weak type from Interface.
Atomic: Such type of properties are used in conditions when we don't want to share our outlet or object into different simultaneous Threads. In other words, Atomic instance make our properties to deal with one thread at a time.
Hopefully it helpful for you.
Related
I am interested in retaining cycles.
Let assume we have two views, A and his subview B.
I know that if B has a (custom) delegate defined as
class B: UIView {
var delegate : CustomDelegate?
}
and I set inside A :
b.delegate = self
This create retain cycle, because B has strong reference to A and A has strong reference to be, so neither could be freed.
Question :
What if I have object inside A and I want to pass it to the B object.
class B: UIView {
var object : SomeObject?
}
and inside A :
b.object = self.object
Is this a retaining cycles too? I can't figure this out.
When object (in A) is created it's reference is 1. When it is passed to the B it's reference is 2. But when A try to deallocate itself : When deallocate object in A it reduce reference to 1 and when he try to deallocate B the object reference should go to 0. Is this mean that there is no retaining cycles? Or did B holds indirect reference to A trough object?
Second question :
What could I lose if all object inside B would be weak references? Or better witch object need to be weak?
I assume your first (and only real) question is intended to imply something like this:
class A : UIView {
var object : NSObject
}
class B : UIView {
var object : NSObject
}
... and then we posit that we have an A and a B where the B is a subview of A. So then the A might say:
(self.subviews[0] as! B).object = self.object // or similar
... and you want to know whether there's a retain cycle involved here. No, not in the general case. There are two objects, an A and a B, and they each have a strong reference to the same third object, i.e. something that is neither this A nor this B. There's nothing wrong with that, and indeed it could be crucial that the A and the B both retain the third object. We might question the legitimacy of A telling B what its object should be, and we might legitimately be disturbed by the possibility that the A could mutate this third object behind the B's back (or vice versa); but from a memory management point of view, nothing of interest has happened.
What could I lose if all object inside B would be weak references
You could lose everything. Remember, normal (strong) references are a way of keeping the referenced object alive (retain); that is what memory management of properties is all about. Assigning to a weak reference, on the other hand, doesn't do that, and thus can cause the assigned object to disappear immediately, if nothing else is retaining it. Weak references are only for cases where the lifetime of the referenced object is correctly and entirely determined elsewhere (as in, a superview determines the lifetime of its subviews).
Can anyone tell me what is the difference among three property of delegation. I searched in google but did not get any satisfactory answer.
Please also tell me which is the best option and why?
#property (nonatomic, strong) id <GameAddViewControllerDelegate> delegate;
#property (nonatomic, weak) id <GameAddViewControllerDelegate> delegate;
#property (nonatomic, assign) id <GameAddViewControllerDelegate> delegate;
The difference is same as with strong, weak and assign specifiers.
Points to be noted : Any object never retains the delegate. Hence strong and retain should not be used.
weak and assign are allowed or even you can go with unsafe_unretained.
Why not to use retain?
Why use weak or assign?
Weak
weak applies to the delegate object (which has reference counts and
all the stuff), but weak references don't increase refcount. But once
the delegate object is deallocated (from anywhere in the code), any
weak reference to that object is set to nil. This is extremely useful,
because if you use only strong and weak references, you can't end up
with an invalid pointer (pointer to an already deallocated object).
Assign
assign is usually used for ints, floats and other non-object types.
You can of course assign an object reference to such a variable, but
if the object is deallocated, you will still have a pointer to it's
memory (which is garbage now, and will hurt you when you use it).
Strong
Strong will keep the object in the heap until it don't point to it
anymore. In other words " I'am the owner, you cannot dealloc this
before i'm fine with that same as retain" You use strong only if you
need to retain the object.
In case of delegation, weak preferred
You generally want to assign delegates rather than retain them, in order to avoid circular retain counts where object A retains object B and object B retains object A. (You might see this referred to as keeping a "weak reference" to the delegate.) For example, consider the following common pattern:
-(void)someMethod {
self.utilityObject = [[[Bar alloc] init] autorelease];
self.utilityObject.delegate = self;
[self.utilityObject doSomeWork];
}
if the utilityObject and delegate properties are both declared using retain, then self now retains self.utilityObject and self.utilityObject retains self.
Also see this detailed answer on stackoverflow
Hi I am a newbie to iOS programming. I know what a strong and weak reference is. But I get confused which type of reference to use when I have to deal with outlets. After going through the documentation which states that
Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong.
So what I understood after going through the above statement is that the Outlets that we create should typically be weak by default.
But while studying some tutorials I have come across the code where people have declared an outlet as strong reference. For example consider the following code :
#interface AboutViewController : UIViewController
#property (nonatomic, strong) IBOutlet UIWebView *webView;
#end
The code :
#property (nonatomic, strong) IBOutlet UIWebView *webView;
says that our AboutViewController has an UIWebView object.
But why we need a strong reference here for the UIView object?? As the document states shouldn't this be an weak reference ?
Also please explain in the documentation statement which I have quoted above what does the File’s Owner to top-level objects mean?.
I have gone through many of the similar questions on this website but none of them helped me to clear my doubt. So please help. Thanks in advance :)
What to use for non top level GUI elements - strong or weak - depends on how you are going to use their outlets. If you have a weak reference
#property (nonatomic, weak) IBOutlet UIWebView *webView;
then after calling method
[webView removeFromSupeview];
your webView will be nil and it will be impossible to restore UIWebView just by adding
[self.view addSubview:webView];
If this is appropriate for you - it is better to use weak because you will free webView's memory when you do not need it.
On the other hand, in case of a strong reference after
[webView removeFromSupeview];
webView will still have referenceCount > 0 and webView will be deallocated only if owner will free it explicitly
self.webView = nil;
or in the owner's
- (void)dealloc
together with the owner itself.
Usually there is no difference if you have static GUI. If you want to remove (not hide) some views add be able to add them later - strong references should be used.
Top level objects should be retained strong. Like
#property(nonatomic,retain) UIView *view;
in UIViewController.
It usually doesn't hurt to use a strong reference in place of a weak one in the case of outlets like this. And in some cases, you do need a strong reference.
The idea is that something has to keep a strong reference to the object at all times or it could vanish. If the object is a view that is a subview of another view, then that superview will keep a strong reference to it and so you can use a weak reference. But, if you're going to do something else with that view, such as remove it from it's superview for some reason (maybe to reuse it elsewhere, or something), then you'll want to use a strong property so that there's always something holding it strongly.
Regarding the File Owner issue, that's because the top level object (most likely a view) does not have a superview holding on to it, so you need to use a strong property so that you're holding on to it.
The simple answer is that unless you are supporting iOS 5, outlets should always be strong.
The purpose of weak outlets was so that in iOS5, if the system unloaded the view controller's view to save memory, any outlets pointing to subviews would be automatically released.
In iOS 6 and later, the system never unloads the view controller's view (viewDidUnload is never called) because Apple found a way to release most of the memory used by a view without releasing the view itself.
Consequently, the outlets in a view controller will never normally need to be released until the view controller itself is released, at which point ARC will clean up all the outlets anyway.
So just use strong for all your outlets and you won't have to worry about obscure bugs or compiler warnings due to using the wrong reference type.
Quoting from Apple's Resource Programming Guide,
Each time you ask the NSBundle or NSNib class to load a nib file, the underlying code creates a new copy of the objects in that file and returns them to you. You need to ensure that you maintain the new object graph as long as necessary, and disown it when you are finished with it. You typically need strong references to top-level objects to ensure that they are not deallocated; you don’t need strong references to objects lower down in the graph because they’re owned by their parents, and you should minimize the risk of creating strong reference cycles.
In case of framework classes like UIViewController the top-level object for the NIB file is the view property. If you check in the documentation it is declared as retain(similar to strong).
#property(nonatomic, retain) UIView *view
So any subviews to this container view should be automatically owned by it. If you now declare these subview outlets as strong they will create a strong cycle and cause memory leaks when the framework tries to cleanup the container view. To avoid these strong cycles all subviews (or non top level objects) should be declared as weak properties.
When can you declare IBOutlet's as strong
Outlets should be changed to strong when the outlet should be considered to own the referenced object:
As indicated previously, this is often the case with File’s Owner—top level objects in a nib file are frequently considered to be owned by the File’s Owner.
You may in some situations need an object from a nib file to exist outside of its original container. For example, you might have an outlet for a view that can be temporarily removed from its initial view hierarchy and must therefore be maintained independently.
You need to check in your code if webView object qualifies for case2 as above. If not the tutorial has got this one wrong and it actually should be weak.
Hope that helps!
Have an interesting issue where there is a class that is referenced in an XIB layout (subclass of UIScrollView) and is not being de-allocated according to Instruments / Allocations and does not break in it's dealloc routine. Let's call it Sclass1.
There is a using class (let's call it Uclass) that has the XIB file and the outlet.
#property (nonatomic, weak) IBOutlet Sclass1* sclass1;
This is hooked properly to the XIB file layout.
Sclass1 is property allocated when the XIB for Uclass is loaded. Uclass does get deallocated and then recreated from time to time and thus we have another instance of Sclass1, but Sclass1 never goes away and can't find another reference to it.
Drill down in Instruments shows the one Malloc and that is it.
fyi, the class gets started with
[UIClassSwapper initWithCoder:]
If an object doesn't get deallocated under ARC, it means a strong reference to it exists. Since your property is weak the object must be owned strongly by something other than the Uclass object (Otherwise it would get deallocated immediately after the XIB has loaded). In the code you've provided it isn't clear what the actual strong owner of this object is, but I assume it could be one (or more) of the following:
Since the object's class is a UIView subclass, it may be (strongly) referenced by its superview if added as one of subviews. This happens automatically when a XIB file is loaded. If the superview doesn't get deallocated neither will the SClass object. You can remove this ownership by calling removeFromSuperview
A strong ownership cycle (retain-cycle) exists somewhere among ivars of the SClass1 object (i.e. one of the strongly-owned instance variables have a strong reference back to its owner - the SClass1). Beware that any block using self directly also keeps a strong reference. Having a strong reference to the block then often leads to a retain-cycle. Save self to a __weak var and pass that to the block instead unless you have a good reason not to.
A manually created strong reference exists by e.g. adding the object to a container or saving the pointer to a non-__weak variable.
Try finding and removing these strong ownerships. Only after all of them are removed the object can be deallocated.
Since your property is weak and it's still not deallocated, look for strong references to Sclass or it's owner, Uclass. Maybe you are using Uclass(or Sclass) in block directly, without __weak typeof(self) weakSelf dancing and this block creates retain cycle. Also watch for parent-child relations and delegates. Maybe there is delegate which is strong instead of weak or two controllers hold strong references to eachother.
Also, if you want to have more detailed answers, please post more relevant code.
I think your #property should be strong for a class :
#property (nonatomic, strong) IBOutlet Sclass1* sclass1;
Because strong is the equivalent to retain and ARC will manage the release for you.
You will have more information with the Apple Documentation about Transitioning to ARC Release Notes in the section on property attributes.
I recently had the same symptoms - To solve it in my case, my object was acting as delegate for a number of other objects, so had to release the object from all its delegate responsibilities before it would call dealloc
in my projects I don't use Interface Builder and I've noticed one thing that I don't know how to explain. Yet. So, to the point. When we are using IB and defining elements of user interface like UILabel or UIButton in our controller we use this ugly prefix IBOutlet and a 'weak' modifier. This works like music. But when we decide not to use IB and define whole user interface from code it just doesn't work.
Let's assume that I want to add UILabel to controller (using IB). I will have something like this i *.h file:
#property (nonatomic, weak) IBOutlet UILabel * label;
And I don't have to do anything more in *.m file. But if I remove the *.xib file and try to setup my UILabel in, for example, one of init methods, like this:
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,100,20)];
self.label.text = #"some text";
[self.view addSubview:self.label];
It doesn't work until I alter my *.h file to this:
#property (nonatomic, strong) UILabel * label;
Now, I know the difference between weak and strong but I have no idea why we can use weak for ui elements when using IB? Something must keep a strong pointers to these elements, right? But what?? In second case it is controller, but I don't understand how it behaves in the first case.
The reason why Interface Builder creates weak references for IBOutlets is as follows:
IB knows that a view is retained by its superview. So any object in the tree of views there's no need to have strong references other than to the root object. The view controller keeps this strong reference in its main view property.
Now when the view in unloaded (at least until iOS 5), the UIViewController's view property is set to nil, releasing the main view. If the IBOutlets to subviews of this superview would be strong references they would keep part of the view hierarchy in memory. That's unwanted (and could possibly lead to confusion when accessing these orphaned views).
Something must keep a strong pointers to these elements, right? But what??
Correct, you must have at least 1 strong reference to an object for it to exist. You'll only need to have a strong reference to the root level objects of the UI, anything below this can be weak (as the parent objects will own their children). The .xib file in co-ordination with its Files Owner would have done this for you.
See this document on the workings of xib files. Specifically, this snippit:
You typically need strong references to top-level objects to ensure that they are not deallocated; you don’t need strong references to objects lower down in the graph because they’re owned by their parents, and you should minimize the risk of creating strong reference cycles.
From a practical perspective, in iOS and OS X outlets should be defined as declared properties. Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create should therefore typically be weak
Despite of accepted answer, this is how you can make it in code:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,100,20)]; // strong ref
label.text = #"some text";
[self.view addSubview:label]; // strong ref from superview
self.label = label; // weak ref
// Now you can do `label = nil;`
This is the point when loading from XIB. The label already has superview when it is assigned to your weak property.