iOS memory management - clarifications - objective-c

I know that alloc and retain will increase the reference count of an object. Is there any other different method that actually increment the reference count? And when/how does dealloc is called?

alloc allocates an object with retain count 1.
Methods that start with new also return an object with retain count 1.
retain increments the count by 1.
release and autorelease (at the end of the run loop) decrement it by 1.
Methods that start with the name of the class (without prefix) return an autoreleased object, meaning that it will be released at the end of the cycle, if you don't retain it yourself.
Finally, methods that copy an object (usually start with copy) also create a copy with retain count 1.
dealloc is called when the retain count of an object drops to 0.
PS. In case you didn't know about it yet, consider using Automatic Reference Counting (ARC).

With these the retain count gets increased.
new, however it can be seen as alloc+init.
retain
copy creates new object with retain count=1
mutableCopy creates new object with retain count=1
dealloc is called automatically as soon as retain count reaches to 0.

Related

Why alloc method can add retain count

When we call alloc with a Class, I know that count of Object will +1. For example: NSObject *obj = [NSObject alloc];, The reference count of obj will be 1. I read the source code, but I can't find some code that can tell me why alloc can add the reference count. And some blog said alloc will call retain method, so it can +1. But I can't find some code can prove this. Can some one tell me why alloc will add reference count?
You cannot find generic code that adds one in +alloc. Usually inside +alloc the object is newly created and gets the RC 1. (So you can say that 1 is added, because the object before its creation has an RC of 0. Of course, this is not formally correct, because before the creation there is no object, therefore it cannot have an RC. Akin of the zero is null antipattern.)
However, classes can overwrite +alloc to return an existing object instead of a new one. For example this has been done in the past for implementing singletons. In such a case +alloc had to signal the new reference (+alloc does an ownership transfer) and really had to add 1. Something like this (sample code):
+(id)alloc
{
if(mySingleton==nil) // it is not already created
{
return mySingleton = [super alloc];
}
return [mySingleton retain]; // ownership transfer
}
I think the idea of saying "+1" instead of "1" in some articles is, that you should view every reference separately. So there is no absolute value of RC. Whatever you do with a reference and its object is relative to the situation before you did it. For this reason some authors always describe the RC with "+1" and "-1". Of course, this is meaningless, if an object is newly created.
alloc does not increase the count. There is not any object until you call alloc, so there is nothing to count. The object comes into existence with one reference, and so it comes back from alloc with a retain count of positive 1.
(Conversely, if there is ever less than one reference, the object is dead.)

Leak in Instruments, Reference Count and Autorelease

Instruments is reporting me a leak of a NSDate variable. But If I add up the retains and releases it should be able to release I think, by the autorelease pool. Probably I'm counting wrong but I wan't to make sure. Take a look at the RefCt.
If I [Class alloc] it should come up with a retain count of 1, then if I autorelease that object, it should be able to free, or is it not?
Instruments adds up the retains and releases for you. That's what the “RefCt” column shows you: The running total.
If I [Class alloc] it should come up with a retain count of 1, …
And indeed it does; that's the first row in the list.
… then if I autorelease that object, it should be able to free, or is it not?
Autorelease isn't an immediate -1; it causes a release later, and that's the -1.
So you have:
Allocation: +1 (=1)
Autorelease: 0 for now; causes a Release later (no change now, so still =1)
Retain: +1 (=2)
Release: -1 (=1)
Retain: +1 (=2)
Retain: +1 (=3)
Release: -1 (=2)
Release: -1 (=1)
Note that one of the three Releases is the one caused by the Autorelease. Only then is -1 incurred.
The object needs another release in order to be deallocated. Until that happens, it won't.
And yes, it is possible for an object that has enough outstanding autoreleases to kill it when they come due to be retained before that happens and thereby be kept alive. I saw this happen once with an object that I was under-retaining, but that was the value of a property being used by a Binding; the Binding retained the value and so kept it alive even after I had autoreleased my own last ownership of it.

Question about NSMutableArray, pointers and release

How exactly does the addObject method of NSMutableArray work? Does it create a new instance and add it into the array or does it simply add a reference to the SAME object into the array?
If the answer is it only insert a reference to the object, then it leads to my next question:
Let's say I have the following method in one of my class ('list' is a NSMutableArray), gladly, this code works the way I wanted, but i just don't seem to fully understand why:
-(void)buyItem:(Item *)anItem
{
Item * newItem = [[Item alloc]init];
newItem.name = anItem.name;
newItem.details = anItem.details;
[list addObject:newItem];
[newItem release];
}
So basically after calling [list addObject:newItem], there would now be total of two reference pointing to the same object right(newItem, and another one in the 'list' array)?
But why does releasing the newItem object here, doesn't wipe out the one in the 'list' NSMutableArray? Aren't they pointing to the same Object?
When you are adding object to NSMutableArray using method addObject: it retains added object. This is why you can release it later and use afterwards by accessing using objectAtIndex: method.
It adds a reference and then increases the objects retain count by one. What you are doing is correct and it will still exist in the array with a retain count of one.
For your reference.
What increases an object's retain count?
It's important to understand the distinction between release and dealloc. release simply decrements the "retain count", except that when the count is decremented to zero, release goes on to dealloc the object.
In general (except where documented otherwise), when you pass an object reference (ie, pointer) to an Objective-C object, and it keeps a copy of that reference beyond the duration of your call to it, it retains the object on its own behalf, and it takes the responsibility to release the object when it is itself deallocated, or when the copy of the reference is nullified or overwritten.

what's the difference between two code scenario

Scenario1:
NSDictionary *dictionary =
[[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.stateZips = dictionary;
[dictionary release];
Scenario2:
self.stateZips = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
dependes on stateZips property.
If it is retained:
Scenario 1: stateZips is properly retained ( a release on stateZips will call its dealloc). also local dictionary is released then and there.
Scenario 2: stateZips is retained twice ( a release in stateZips will not call its dealloc as it is still retained).
If it is assigned:
Scenario 1: stateZips points to released dictionary and accessing it else where might result in crash.
Scenario 2: stateZips is properly retained ( a release on stateZips will call its dealloc).
copy is not being considered, as i believe its not your intention (at least in this piece of code)
Both cause self.stateZips to be set to a dictionary initialized with the file pointed to in plistPath.
But in the second, the pointer to the initialized dictionary was not saved, and as it's an object with a retain count of +1 technically a release message needs to be sent to it in some place, to balance the memory management. But as there is no way to retrieve the pointer to that object, you'll end up with a memory leak.
Two exceptions apply:
1.Garbage Collection
If you're in a garbage collected environment, both are the same. Well, they are not the same, but the result is similar.
2.Property type
If the setter for stateZips simply assigns the pointer, then you can release the object using the ivar pointer. Then these two pieces of code have only one difference: in the former, the object is released right after it's used. In the latter, it's just "undefined". Without the context, it's hard to determine if this object was released or not, and when.
I am assuming that stateZips is a property with the retain attribute.
In Scenario 1. A dictionary is created with a retain count of 1 in the first line. In the second line the property will call retain again, increasing the retain count to 2. Finally the retain count is decremented by the release. This will leave the dictionary with the correct retain count.
In Scenario 2, the retain is only called once.
The net effect of the two scenarios is the same. The dictionary object will be retained, and you will need to include a release in the dealloc method of the class.
If this were not correctly handled by the compiler, it would be very hard indeed following the retain/release rules of objective-c.

Will the retain count increase when added to an array?

I just wanted to know: will the retain count of an object be incremented if it is added to an array or dictionary in Objective-C? Can I release a particular object immediately after adding it to an array or dictionary?
Yes, it will increase the retain count of the object you added, that is why you can release the object immediately after adding it to the array.
NSObject obj1;
obj1=[[NSObject alloc] init];
//obj1's retain count is 1 here.
[array1 addobject:obj1];
//obj1's retain count incremented by 1, so the total retain count is 2.
[obj1 release];
//obj1's retain count decremented by 1, so the total retain count is 1.
array1 will keep the object until the array1 itself is not released.
Hariprasad,
NS[collection name here] retain objects added to them as NSResponder noted. A few other facts:
To your comment "can I release it
after adding", the short answer is
yes. Often times I do an
autorelease for objects that are
bound for containment in a
collection and won't be needed outside the collection.
When you remove an
object from a collection, the
reference count is decremented. If
you want to ensure it won't be
deleted from memory (next pool
sweep) you need to retain the
object.
NSArrays retain any object added to them.