Does removing an object from NSArray automatically release its memory? - objective-c

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
myClass *obj = [[myClass alloc] init];
NSArray *ar = [NSArray array];
[ar addObject: obj];
[ar removeObject: obj];
[pool drain];
Will removing an object from an NSArray array automatically release its memory that I have earlier allocated?? The answer seems to be yes from what I have found from various sources. The problem is if I test for memory leaks, xcode still complains that obj has not been released. So what's actually going on?

Collections retain the objects you add to them, claiming temporary ownership. When you remove an item from the collection, it releases the object (and its temporary claim). In other words, the retain count will be the same before you add an object to a collection and after you remove it.
If that retain count is 0, the memory is reclaimed.
In your code you're allocating an object and claiming ownership of it. That means it has a retain count of 1.
Then you're adding it to the array. The array retains the object, taking temporary ownership and upping its retain count to 2.
You then remove the object from the array. The array releases the object and relinquishes any claim of ownership, bringing the retain count back down to 1.
Since memory is not reclaimed until retain count is back to 0 (nobody has a claim on the object), your object's memory is not reclaimed.
If you had autoreleased the object prior to adding it to the array, or called release on the object after you had removed it (but not both!), the retain count would be 0 and the memory would be reclaimed.

Yes. When you insert an object into an array, the array retains it (bumps its retain count). If the object's retain count is 1 (ie, there are no other retains on it) then when it's removed from the array the retain count goes to zero and it's eligible to be deleted.
But your problem in the above scenario is that, after adding the object to the array, you failed to release YOUR retain on the object (due to the alloc/init). Insert [obj release] after the [ar addObject:obj].
(Also note that in your example the entire array will go "poof" when you drain your autorelease pool.)

No, you alloc it -> retain count of 1
You add it to the array which sends the object another retain -> 2
You remove the object from the array and the array sends a release -> 1
...so now the retain count is back to 1, which is your initial alloc retain, so you need to release it to free the memory.

Related

What will happen to the previous memory of allocated objects?

If I have an array with some values i.e allocated some memory.
What will happen to the previous memory if i will alloc new memory for the array.
self.array = [[NSMutableArray alloc] initWithObjects:anObject, nil];
self.array = [[NSMutableArray alloc] initWithObjects:anObject2, nil];
What will happen to memory of objet anObject, Will it be preserve in memory or it will automatic remove from memory after allocating new memory ?
The object on your first array, #"1" is actually a pointer to an NSString object.
Once the pointer is released by overriding the value in your array, the memory the NSString instance occupied will be deallocated. The new string object (#"2") is not neccessarily stored in the same memory.
On allocating memory second time previous data will be lost like
self.array = [[NSMutableArray alloc] initWithObjects:#"2", nil]; on doing this objects from previous memory location
self.array = [[NSMutableArray alloc] initWithObjects:#"1", nil];
will no longer exist.
What will happen to memory of objet anObject, Will it be preserve in memory or it will automatic remove from memory after allocating new memory?
It is impossible to answer this question definitively as it depends on other factors which are unknown.
What I think you are trying to understand is the memory ownership model of arrays (NSArray, `NSMutableArray). In the hope this guess is correct:
First think in terms of ownership. An object is created by its first owner, can over its lifetime have multiple owners, and will die sometime after it has no owners. Under ARC ownership is handle for you in combination with attributes such as strong and weak. Under MRC ownership is manual using methods such as retain and release.
Arrays, and dictionaries, sets, etc., use the model:
When an item is added to the collection ownership is taken for that item.
When an item is removed from the collection ownership is relinquished.
When a collection itself becomes unowned it relinquishes ownership of all the items it contains.
So in your particular case what happens to anObject depends at least on:
Whether the first NSMutableArray has other owners.
Whether anObject itself has other owners.
There are also objects which are effectively owned by the application, so they never appear to die (they die when the app terminates). A common immortal object is a string literal, so if anObject is a string it may well live on.
HTH

Memory management in local variable objective-c

In one interview i was asked to implement NSArray's exchangeObjectAtIndex:withObjectAtIndex: method.
I wrote the following code:
- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 {
id tmp = [self objectAtIndex:index1];
[self replaceObjectAtIndex:index1 withObject:[self objectAtIndex:index2]];
[self replaceObjectAtIndex:index2 withObject:tmp];
}
Interviewer said here's a memory management problem in first line and I'm going to catch bad_access_exc.
He recommended to write as this:
- (void)exchangeObjectAtIndex:(NSUInteger)index1 withObjectAtIndex:(NSUInteger)index2 {
id tmp = [[[self objectAtIndex:index1] retain] autorelease];
[self replaceObjectAtIndex:index1 withObject:[self objectAtIndex:index2]];
[self replaceObjectAtIndex:index2 withObject:tmp];
}
I understand that his code is right, but since tmp is local variable and it's going to be assigned, so there's no releasing and everything is gonna be ok. Is there any error?
If you are using manual memory management, there is an error. Apple has documented the problem under “Avoid Causing Deallocation of Objects You’re Using” in the Advanced Memory Management Programming Guide.
Specifically, objectAtIndex: doesn't retain and autorelease the object that it returns to you. So the NSArray might have the only “owning” reference to the object. Assigning to tmp under manual retain counting (MRC) doesn't retain the object so tmp doesn't own it and the autorelease pool doesn't own it.
This means that when line 2 of your method sends [self replaceObjectAtIndex:index1 withObject:[self objectAtIndex:index2]], the array might release the last reference to the object, deallocating it. At that point, tmp refers to a deallocated object; this is called a “dangling reference”.
Then in line 3, you try to put the dangling reference in the array. The array will send retain to the reference, which is invalid, and you will crash or experience heap corruption.
Under ARC, assigning to tmp does retain the object, so there is no error in that case.
Remember that id tmp is nothing more than a pointer to the object in your array. It doesn't say anything about the memory management of the object it's pointing to.
...it's going to be assigned, so there's no releasing...
This is the sticking point here. You can't guarantee that the object at index1 won't be deallocated when you replace it with the object at index2. In fact, the array will call release on it at this point to balance out the retain it called on the object when it was originally added to the array. Thus, it's possible that when the object at index1 is replaced will the object at index2, the reference count of the object at index1 will go to zero, the object will be deallocated, and your tmp variable will turn into a dangling pointer. The ... retain] autorelease] dance keeps the object around long enough to do the swap without having to worry about it deallocating before the end of the method (likely it will stick around until the top of the next run loop).

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.

Reference count is still 1 after [obj release], when it should be deallocated

When I create an object and check its retain count, I get 1 as expected. When I release the object and then check the retain count again, it is still 1. Shouldn't the object be deallocated, and the retain count 0?
NSMutableString *str=[[NSMutableString alloc] initWithString:#"hello"];
NSLog(#"reference count is %i",[str retainCount]);
[str release];
NSLog(#"reference count is %i",[str retainCount]);
I do see 0 for the retain count if I set str to nil first. Why is that?
Don't use retainCount, it doesn't do what you expect in most cases.
Your second NSLog is accessing deallocated memory as an object. In this particular case, that deallocated memory still contains enough of the old data from the NSString that was just freed for the program to not crash when the retainCount method is called on it. Had you run this with NSZombieEnabled you would have gotten an error message about sending a message to a deallocated instance.
The reason it returns 0 when called for nil is that methods returning integers will always return 0 when called on a nil object.
Do not depend on retainCount. And do not care about this. Lots of things may happen under the hood. You only need to ensure that you have released all the things that you owned. If you are trying to be sure that you are not leaking any memory, then use Instrument, not retainCount in NSLog.

NSArray (and other containers) behavior on dealloc

When Objective C containers are dealloc'd, do they release their references to the objects they contain or do I need to do that manually?
Should have read the docs for NSArray closer:
Arrays maintain strong references to their contents—in a managed memory environment, each object receives a retain message before its id is added to the array and a release message when it is removed from the array or when the array is deallocated. If you want a collection with different object ownership semantics, consider using CFArray Reference, NSPointerArray, or NSHashTable instead.
They release their references to the objects that they contain.
When you add an object its reference count is incremented. When it's removed (wither manually or when the array is destroyed) its reference count is decremented.
So with the following code you would not have to release the object
NSObject* someObject = [[[SomeClass alloc] init] autorelease];
[someArray addObject: someObject];
When an array is deallocated, each element is sent a release message.