Differences between strong and weak in Objective-C
Asked Answered
B

9

324

What are the differences between strong and weak in @property declarations of pointers to objects?

Also, what does nonatomic mean?

Blase answered 13/6, 2012 at 11:8 Comment(3)
actually this is a good questions, sometimes, we forgot how the basic concept of strong/weak and atomic/nonatomic preferences.... :) Thank you for reminding us about it...Ectoenzyme
@JackyBoy Whats funny is that the proposed simple search on google lead me here lol. #circularreferenceBalcony
I tend not to trust many of the answers on google but always refer to S.O for intelligent answersDashiell
V
659

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:

  1. delegate properties, which are often referenced weakly to avoid retain cycles, and

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

Virgenvirgie answered 13/6, 2012 at 11:16 Comment(4)
@Bourne: That depends on what you mean by thread safety. atomic guarantees that the property can be safely read and written from several threads at the same time. That does not mean an object whose properties are all atomic is automatically thread-safe.Virgenvirgie
As per apple documentation, atomic and nonatomic should be synonymous with thread safety. developer.apple.com/library/ios/documentation/cocoa/conceptual/…Suffragan
"Note: Property atomicity is not synonymous with an object’s thread safety." developer.apple.com/library/ios/documentation/cocoa/conceptual/…Astigmatism
why don't we just delete the instance when we don't want ? Why can't we just take the air out of the balloon or destroy it when we don't want, why do we have to care about the strings attached? We just need data.Glochidiate
R
745

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.

Raffinose answered 20/8, 2013 at 21:4 Comment(10)
After 1 and a half years of iOS developing, I think just now I clearly understood what strong and weak actually mean.Podiatry
What's the harm in having another string though? As in, why not reference everything with strong so you don't have to worry about it and accidentally crash the app on an unexpected null variable?Unstriped
@Unstriped I have the same doubt, why not use strong for everything? Because of the retain cycles. However, how to explain the retain cycles in the "ballon" way? A ballon holds a string of another ballon and vice versa?Embroil
@X.Li Retain cycle is like you have 2 strings to the ballon, one of them is owned by you (so you own this ballon), the other is owned by the ballon (so this ballon owns you). Since you only have access to your string, how do you let the ballon go if the ballon doesn't wanna go? So it's better you own the ballon (strong) while the ballon doesn't own you (weak). When you want to let it go, just cut the string :)Blastoderm
@Raffinose I have edited the answer to include the explanation of retain cycle. Please feel free to edit/remove the comment.Woodworm
Your answer remains with the next question OP asked. "What is nonatomic?"Bylaw
Atomic vs non-atomic I think can be described as a public toilet room with with multiple doors, with one toilet at the center. Once somebody get into the toilet through one door, he might as well lock all of the other doors into the toilet if he doesn't want to experience moment of awkwardness. Lol. Thank you for reading this nonsense analogy.Crotty
Hats off ! Very creative and very clear explanation. Thank you so much. I guess this should be marked as the correct answer !Vaniavanilla
I know this is nearly four years old now, but this analogy is great. I have a followup, what is the equivalent of strong/weak,atomic,nonatomic in C++, C#, as they are my background, I am having a hard time with the entire concept why it is even needed, but if I see what is done in other languages I can get that full a'ha click moment.Zapata
what if __strong __auto_type self = self_weak_ ?Gove
V
659

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:

  1. delegate properties, which are often referenced weakly to avoid retain cycles, and

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

Virgenvirgie answered 13/6, 2012 at 11:16 Comment(4)
@Bourne: That depends on what you mean by thread safety. atomic guarantees that the property can be safely read and written from several threads at the same time. That does not mean an object whose properties are all atomic is automatically thread-safe.Virgenvirgie
As per apple documentation, atomic and nonatomic should be synonymous with thread safety. developer.apple.com/library/ios/documentation/cocoa/conceptual/…Suffragan
"Note: Property atomicity is not synonymous with an object’s thread safety." developer.apple.com/library/ios/documentation/cocoa/conceptual/…Astigmatism
why don't we just delete the instance when we don't want ? Why can't we just take the air out of the balloon or destroy it when we don't want, why do we have to care about the strings attached? We just need data.Glochidiate
D
25

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.

Dodecasyllable answered 13/6, 2012 at 11:14 Comment(0)
B
13

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.

Bronchiole answered 10/6, 2016 at 6:39 Comment(3)
And what does etc contain :PCoextensive
webView, mapView,etcBronchiole
actually most of the subview that we drag and drop on storyboardBronchiole
E
9

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

Echolocation answered 26/11, 2014 at 13:27 Comment(0)
R
7

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

Rude answered 20/8, 2013 at 19:53 Comment(0)
C
7

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.

Contemplation answered 2/9, 2013 at 14:28 Comment(0)
K
4

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.

Koal answered 12/10, 2018 at 11:19 Comment(3)
2019-07-25 12:33:15.479002+0530 StrongAndWeak[6329:245483] My name is = ABC 2019-07-25 12:33:15.479226+0530 StrongAndWeak[6329:245483] My name is for strong = ABC 2019-07-25 12:33:15.479418+0530 StrongAndWeak[6329:245483] My name is for weak = ABC in this you told weak property don't have value of myname .But I am getting myname value as ABC for both references ....?can you give more clear answer....Thanks in AdvanceMixed
@Raviteja_DevObal ARC does not promise to do it immediately(i.e. deallocate the string @"ABC"), but it will get deallocate for sure later on...Koal
@Raviteja_DevObal As Explain here strings are a bad example for this. I have updated my answer with UIView object, hope it helps.Koal
E
1

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.

Earthstar answered 23/1, 2017 at 11:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.