I have created a class called Item that has two pointers to Item, *containedItem and *container. I declare them as follows:
#property (nonatomic) Item *containedItem
#property (nonatomic) Item *container
I override dealloc within Item as follows:
- (void)dealloc
{
NSLog(#"Destroyed: %#",self);
}
so that I may see which items are being destroyed. I create two items and make it so that one points to the other as its container and the other points to the first as its contained. As the default attribute is being a strong pointer, I would think this would lead to a memory leak. However, when I run my program, it shows that both Items are destroyed. I am wondering how the Items can be destroyed when both have a strong pointer to them (from the other).
Related
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.
I have an Manual Reference Count project, where few classes Im converting to ARC by removing retain,release & etc and by setting compiler flag “-fobjc-arc”
Their are 2 ARC(-fobjc-arc) enabled view controller classes, ClassA and ClassB.
I am allocating and initialising objects of ClassB inside ClassA within a for loop to achieve some functionality, Code snippet is as below,
#interface ClassA ()
#property (strong, nonatomic) ClassB *classBObj;
#end
#implementation ClassA
- (void)createClassBView {
for (int count = 0; count <= [dataObject count]; count++) //if count is more than 1 it is not retaining the previous classBObj
{
classBObj = [[ClassB alloc] init]; //ARC is keeping only 1 object reference of this class but I need to retain all the iterated objects
[self.scrollView addSubView:classBObj withFrame:myFrame];//only 1 view is getting added as subview even if control comes here more than once
}
}
#end
The above code works fine for me in non-ARC(MRC) but fails to work properly when ARC is enabled. It is not retaining ClassB objects even if it is strong,
Only 1 object i.e; last iterated ClassB object reference is alive, rest are getting destroyed and it is throwing exception "ClassB reference to an deallocated instance"
I tried by using if(!classBObj){classBObj = [[ClassB alloc] init];} inside loop, that time I'm not getting ClassB reference to an deallocated instance exception but only 1 subview of ClassB is getting added to my scrollview(i.e; last iterated).
Please guide me on this.
Any help is appreciated in advance.
Your code is doing exactly what you are telling it to do. You are setting the very same reference, self.classBObj, to a ClassB instance - over and over, in your loop. Each time through the loop, the existing ClassB instance that was previously assigned self.classBObj needs to "get out of the way" so that a new one can be assigned to self.classBObj. So it is rightly released when it is replaced by the new one - rightly, because there is now no existing reference to it.
The truth is that you were totally mismanaging the memory here before ARC, and adopting ARC has revealed this fact. You're just lucky your code ever worked (or seemed to). If you want to maintain multiple ClassB instances, you need your instance variable to be an array of them, not a single one.
(On the other hand, if classBObj is a UIView and is to be added immediately to the interface as a subview, that is still happening, so it's hard to see what your complaint is. Indeed, the weird part is why you ever needed classBObj to be a property in the first place; why isn't it just a local variable? It's not like you need these references to be retained elsewhere, since you have those references — as subviews of your self.scrollView. But if you need those references for some later purpose, and if you don't want to obtain them by using the fact that they are subviews of your scroll view, then clearly you need an array of them, as I just said.)
I'm building an app whereas I have a ViewController viewing a custom object, lets call this object "CustomObject". Upon a button press, a segue is triggered and hence prepareForSegue is called where I get the destination ViewController and pass self.myObject. The destination ViewController may change a few parts of the CustomObject, but those changes should not be reflected in the original ViewController if the user decides to go back to the original ViewController. The changes should only be reflected if the user pressed "Save" in the destination ViewController and hence triggering an NSNotification with a version of the CustomObject that should be reloaded in the original ViewController like so:
self.myObject = (CustomObject *)notification.object;
So my question is as follows: Which of these should I use (or any other that would be correct) - and why?
#property (nonatomic, strong) CustomObject *myObject;
#property (nonatomic, copy) CustomObject *myObject;
Thanks!
Update:
header file:
#interface CustomObject : NSObject <NSCopying>
implementation file:
- (id)copyWithZone:(NSZone *)zone
{
id copy = [[[self class] alloc] init];
if (copy)
{
// Copy NSObject subclasses
[copy setRegisterDate:[self.registerDate copyWithZone:zone]];
}
return copy;
}
You should use strong but (in prepareForSegue) create and pass a copy (or simply a different object, but in any case, don't pass the original object).
This is the opposite of the situation for which the copy property attribute was designed. With the copy property attribute, the recipient wants to ensure that the object is not mutated later behind his back: e.g., I accept an NSString but the caller passes me an NSMutableString and retains it as well, so that my string can now be changed behind my back. By calling copy, I turn the NSMutableString into an NSString, which is immutable.
Your situation, as I said, is just the opposite. Your first view controller wants to pass an object without any risk of affecting his own object. Therefore, it is up to your first view controller to make a new object and pass it, rather than passing a pointer to his own sacred object. It is not your second view controller's job to know that your first view controller needs protecting; it is up to your first view controller to protect himself.
I feel you can go for copy. Since it can be used when the object is mutable. Use this if you need the value of the object as it is at this moment. 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.
Pl. refer to the below link also which gives good insight when to use which property.
Objective-C declared #property attributes (nonatomic, copy, strong, weak)
You should use "copy", because "copy" creates a duplicate instance of that object, and the new object is independent of the original object. "strong" adds a "link" to the object, it's only one object.
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
All the examples I've come across so far ( including Stanford podcasts ) reference a Model by declaring it as a property of a View Controller and using it from there:
#import "myClass.h" // assume it carries a single NSString property
#interface
#property (nonatomic,strong) myClass *myobject;
#end
#implementation ViewController
-(void)viewDidLoad {
self.myObject = [[myClass alloc] init]
.
.
.
-(void)someMethod{
displayLabel = self.myObject.myString;
seems like that's more self.C-V than M-V-C.
After messin' about on my own this works:
#import "myClass.h"
#implementation ViewController {
MyClass *myObject;
}
-(void)viewDidLoad {
myObject = [[myClass alloc] init]
}
.
.
.
-(void)someMethod{
displayLabel = myObject.myString;
my question is; is there any danger in using second example? or to ask differently, does it give the compiler an easier task of keeping MODEL separate from VIEW and CONTROLLER?
There are a couple of implementation details that are different between your two examples but they are essentially doing the exact same thing.
In both cases you are declaring a backing ivar. This line #property (nonatomic,strong) myClass *myobject; will implicitly #synthesize myObject = _myObject;, which is similar to you manually writing:
#interface ViewController : UIViewController {
MyClass *_myObject;
}
// or
#implementation ViewController {
MyClass *_myObject;
}
The only other difference is that #property (nonatomic,strong) myClass *myobject; will also create the accessor methods for you
- (void)setMyObject:(MyClass *)myObject;
- (MyObject *)myObject;
This is indeed still MVC but controllers that are subclasses of UIViewController always manage at least one view. The M component is your myObject instance. As in most diagrams the Controller sits there managing the communications between the V and M both of which the controller owns
Using singletons or holding the model as a property of the controller is also a question of lifetime. I prefer using singletons for helper classes (getting data from game center or fetching data from core data). Singletons are useful for things you need to access from different places within your app (where lifetime of your singleton is longer than your view controller's lifetime). But for view controller dependent models you can of course use them as properties of the view controller. Let's say you have ten view controllers in your app each displaying completely different content it does absolutely not make sense to keep all data for all possible view controllers in memory (in a singleton) just to have data ready in case the user wants to see any of the view controllers. In this case it's no shame to load your model's data from within your view controller implementation and hold it as a property. This guarantees that data is auto released when the view controller's lifetime ends and avoids conflicts. Holding data in singleton would make sense when you display data loaded from a server that does not need to be refreshed everytime you present your data to reduce the amount of traffic generated by loading the data. Using singletons might be dangerous regarding thread safety e.g. when data is mutated from a background thread while iterating over your datasource object to refresh a table view's content. Singletons can also lead to tigh coupling which should be avoided. Using an instance variable instead of a property is still a good choice if you want to hold a weak reference to an object as it is automatically set to nil if the referenced object gets auto released. A weak property would in this case lead to bad access.