Retain or copy UIKit elements - objective-c

First Question
When an object's property is retained in Objective-C, why does a second instance of the same class point to the same object? If you instantiate a new class, then you would logically want a separate class with separate properties. retain I understand increases the retain count only and copy will shallow copy.
I've created a class which has a retained NSURLRequest. I initialized two instances of that class. Changing the property on any of the created classes will change them for all. When I used copy on the property, it stopped doing that. Reading online however, it says that copy on an immutable object is essentially a shallow copy since you really do not want a separate entity since it can never be changed. In this case, NSURLRequest is immutable so how did my example work by invoking copy on an immutable object when it supposedly deep copied it? Here's how I copied it:
- (id)initWithRequest:(NSURLRequest *)request {
self = [super initWithNibName:nil bundle:nil];
if (self) {
_request = [request copy];
}
return self;
}
Second Question
I've been reading that essentially for all immutable objects, I need to use copy and for mutable objects use retain (or now in ARC, strong). If IBOutlets are weak pointers, what if I draw my views without Interface Builder? Would UIKit elements be copy or retain/strong?
Thanks!

A retain tells iOS not to release that memory even if the original property or pointer sets itself to nil which would decrement the retain count. So if you do a shallow copy which would be assigning one pointer to an existing object it will retain it. If you need to do a deep copy then you should specify copy or create a copy constructor.
A weak reference is similar to using the old method of "assign" on a piece of memory that you do not want to increment the retain count on. There are situations where you can have circular references and could potentially never release the memory. If you do not use IB to create UIKit objects ARC will be sure to retain the memory for you assuming you have a valid pointer to that object. For instance if you have a UIButton pointer as a member of a view controller and you dynamically create a button it will retain that memory for as long as that pointer is valid and release it once the pointer is set to nil.

Related

I want to know the difference between strong, retain, and weak [duplicate]

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.

Differences between strong and weak in Objective-C

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.

Objective C ARC release without assigning a variable

In Objective C ARC, is it safe to do [[[MYObject alloc] init] callingSomeMethod]? Will it get released even if I dont assign to a variable?
Yes it will. If you're nervous about it, it's easy to verify. Just put NSLog(#"it did!"); in that object's -dealloc method and check to make sure it logs.
If you don't need the object to live after callingSomeMethod returns, it is safe to do [[[MyObject alloc] init] callingSomeMethod].
If you need the object to live after callingSomeMethod returns, then your program needs to create a strong reference to it before callingSomeMethod returns. Examples:
If callingSomeMethod sets the object as the target of an NSTimer, you are safe because NSTimer retains its target.
If callingSomeMethod only sets the object as the delegate of a UITableView, you are not safe, because UITableView does not retain its delegate. In that case, you must also create a strong reference to the object somewhere else.

How do I fix a memory leak?

After doing a long profile test, I found that in one of my ".m" file memory leak occurs in the viewdidload section. i checked and the xcode highlighted the part where i have initialized picker arrays with values. my program uses pickers for user input. and i have 3 5 different views in my program. the first is a disclaimer ,the second is a menu where the user can choose the type of calculation he/she wants to do. each calculation requires certain inputs which the user enters from a picker. for eg. one of the view has 5 inputs which are handled by 5 different uipickers with seperate arrays for holding the values. these arrays are initialized with the values in the viewdidload method of that view. here is what i found after running the test:
...................................................................................................
This is my first time developing an app and i'm kinda confused about what to do. Any help would be appreciated.
Objects in objective c have a retain count. If this retain count is greater that 0 when the object goes out of scope (when you stop using it), it leaks.
The following things increase the retain count
[[alloc] init]
new
copy
[retain]
adding an object to an array
adding an object as a child (e.g. views)
There are likely more, but you don't appear to use any others in your code
The following decrease the retain count
[release]
removing an object from an array
if you dealloc an array, all of its objects are released
You should go through your code and ensure each of the retains or additions to an array are matched with a corresponding release. (You can release member variables in the dealloc method).
EDIT: Jeremy made a valid point that my answer doesn't
Once you add an object to an array, it takes ownership and will release the object when it is done with it. All you need to do is make sure you release anything you own according to the memory management rules
There are also autorelease objects, have a look at this example;
-(init){
...
stagePickerArray = [[NSMutableArray alloc] init];
for (int i = 0; i < 3; i++)
{
//this string is autoreleased, you don't have call release on it.
//methods with the format [CLASS CLASSwithsomething] tend to be autorelease
NSString *s = [NSString stringWithFormat:#"%d", i);
[stagePickerArray addObject:s];
}
...
}
I think the only thing you are missing is a call to release in your dealloc method
-(void) dealloc
{
[stagepickerarray release]; //Do this for each of your arrays
[super dealloc];
}
The leaks tool will only tell you where yo allocated the objects that it thinks leaks. So, it's telling you, for instance, that
NSString* answer = [NSString stringWithFormat: ...
allocates an object that is never deallocated. Now, -stringWithFormat: gives you an object that you do not own and you don't seem to retain it anywhere. Therefore, you do not need to release it, so it can't be leaking by itself.
That means something else that you do own must be retaining it and you never release that something else. The prime suspect would appear to be stagePickerArray. Check that you are releasing stagePickerArray somewhere. If it's local to -viewDidLoad it must be released or autoreleased before the end of that method. If it's an instance variable, it must be released in the class's -dealloc method.
In Objective-C you need to take care of the retain count of allocated memory. If you don't need it -> release it.
Whenever you alloc an object, it will return an object with retain count = 1.
By using retain, the retain count gets incremented,
by using release, the retain count gets decremented.
Whenever the retain count is equals 0, the object will be destroyed.
So whenever you want to use the object somewhere else you need to retain it. So you make sure that the object is not deleted after the other 'person' (or whatever it used ;)) called release.
This was a very very very short description. Check the following guide
Memory Management Guide for iOS.
(Also you want to read something about ARC - Automatic Retain Counting - which is new in iOS5! ios5 best practice release retain

How to add alive object to NSMutableArray and remove them when they're released?

I have class Item and class List (which has an NSMutableArray).
Every time class Item is instantiated (and destroyed) it posts a notification, which is listened-to by class List. When class List receives the notification is adds the instance of class Item to its list.
I'm trying to have class Item also post a notification that its about to be dealloc'd. The problem is that class List's NSMutableArray retains the instance of class Item.
What's the most appropriate means of handling this situation? If I decrement the count when adding it to List's array, then an exception will be thrown when class List attempts to call removeObject (since it'll try to dealloc the object.)
Basically, I want a "monitor" class List that contains a list of all "live" instances of Item. But, I also need the ability to release/dealloc the instances and have them report they're being dealloc'd so List can remove them from its NSMutableArray.
Thanks for your help.
If I understand correctly, you want an array that maintains weak references to its items, as opposed to strong references?
I don't know of a way to do this with anything "built-in" in Cocoa. The only way I'd know of to do this is to make the array yourself, and have the storage be __weak id[]. That would automatically zero-out the place in the array when the object deallocates. If you're under the retain-release model, you could use something like MAZeroingWeakRef to get the same behavior.
This is definitely an interesting question, and I don't know of an easier answer. I'd love to be proven wrong!
Ha, I love being wrong!
There's a class called NSPointerArray that looks like it can do what you're looking for. However, it's only available on the Mac, and it only auto-zeros when you're using garbage collection.
I'll keep thinking about this. This is an interesting problem! :)
So I kept thinking about this, and came up with a solution. It uses two unconventional things:
A subclass of NSMutableArray (egads!)
Using an associated object to determine object deallocation
For the first bit, I had to to subclass NSMutableArray so that I could inject some custom logic into addObject: (and related methods). I didn't want to do this via swizzling, since NSArray and friends are a class cluster, and swizzling into/out of clusters is fraught with peril. So, a subclass. This is fine, but we're going to lose some of the awesome features we get from "pure" NSArray instances, like how they do weird things when they get big. Oh well, such is life.
As for the second bit, I needed a way for any arbitrary object to notify that it is about to or just finished deallocating. I thought of dynamically subclassing the object's class, injecting my own dealloc/finalize method, calling super, and then smashing the isa of the object, but that just seemed a little too crazy.
So, I decided to take advantage of a fun little thing called associated objects. These are to ivars what categories are to classes: they allow you to dynamically add and remove pseudo-instance variables at runtime. They also have the awesome side effect of getting automatically cleaned up with the object deallocates. So what I did is just created a little throw away object that posts a notification when it is deallocated, and then attached it to the regular object. That way when the regular object is deallocated, the throw away object will be as well, resulting in a notification being posted, which I then listen for in the NSMutableArray subclass. The notification contains a (stale) pointer to the object that is in the process of getting destroyed, but since I only care about the pointer and not the object, that's OK.
The upshot of all of this is that you can do:
DDAutozeroingArray *array = [DDAutozeroingArray array];
NSObject *o = [[NSObject alloc] init];
[array addObject:o];
NSLog(#"%ld", [array count]); //logs "1"
[o release];
NSLog(#"%ld", [array count]); //logs "0"
The source is on github, and it should (theoretically) work just as well on iOS as Mac OS X (regardless of GC mode): https://github.com/davedelong/Demos
Cheers!
... and I just thought of a way to do this without a custom subclass, but I'm tired and will post the updated answer tomorrow.
the next morning...
I've just updated the project on Github with an NSMutableArray category that allows you to create a true NSMutableArray that auto-zeroes its objects as they're deallocated. The trick was to create a CFMutableArrayRef with a custom retain callback that sets up the proper observation, and then just cast that CFMutableArrayRef to an NSMutableArray and use that (ah, the magic of Toll-Free Bridging).
This means you can now do:
NSMutableArray *array = [NSMutableArray autozeroingArray];
I added a typedef to define these as NSAutozeroingMutableArray, just to make it explicitly clear that while this is an NSMutableArray, it doesn't retain its objects like a normal NSMutableArray. However, since it's just a typedef and not a subclass, you can use them interchangeably.
I haven’t tested this, so comments are welcome.
You could use an NSPointerArray for the list (in a retain property):
self.array = [NSPointerArray pointerArrayWithWeakObjects];
When an Item object is created, it would post a notification that’s listened by your List class. Upon receiving the notification, List adds the object to the pointer array:
[array addPointer:pointerToTheObject];
In this setting, the pointer array doesn’t keep a strong reference to its elements — in particular, it doesn’t retain them. This applies to both garbage-collected and non-garbage-collected builds.
In a garbage-collected build, if an element is garbage collected then the garbage collector automatically assigns NULL to the position in the array where the object was stored.
In a non-garbage-collected build, you’ll need to manually remove the element or assign NULL to the position in the array where it was stored. You can do this by overriding -[Item dealloc] and posting a notification that the object is being deallocated. Your List class, upon receiving the notification, would act upon it.
Note that, since objects are not owned by the pointer array, you must keep a strong reference to (or retain) them if you want to keep them alive.