What will happen to the previous memory of allocated objects? - objective-c

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

Related

initWith vs arrayWith in objC?

What are the pros and cons of creating an array (or any other collection using its respective factory method) with
[[NSArray alloc] init]
vs
[NSArray array]
in objective C? It seems like the latter factory method allows us to not worry about memory management, so I was curious if there's any point in ever using alloc + init, though I'm now more interested in all the differences between these two, and why one would choose one over the other.
Prior to ARC there was a critical difference. The alloc/init case returned a retained object, while the array case returned an autoreleased object.
With ARC the difference is less important. Probably the first case is a hair more efficient, but in most scenarios they are interchangeable.
In the first one, you have the ownership of array object & you have to release them.
NSMutableArray* p = [[NSMutableArray alloc] init];
[p release];
& last one you dont need to release as you don't have the ownership of array object.
NSMutableArray* p = [NSMutableArray]; //this is autoreleased
If you call release in this, then it will crash your application.

Memory allocation for an array of Objects - Is my understanding valid?

I have a question regarding memory allocation for Objects in an array. I am looking to create an array of Objects, but at compile time, I have no way of knowing how many objects I will need, and thus don't want to reserve more memory than needed.
What I would like to do is allocate the memory as needed. The way I would like to do this is when the user clicks an "Add" button, the array is increased by one additional object and the needed memory for the new object is allocated.
In my novice understanding of Objective C (I was a professional programmer about 20 years ago, and have only recently begun to write code again) I have come up with the following code segments:
First, I declared my object:
NSObject *myObject[1000]; // a maximum number of objects.
Then, when the user clicks an Add button it runs a method with the allocation code: (note: the variable i starts out at a value of 1 and is increased each time the Add button is clicked)
++i
myObject[i] = [[NSObject alloc] init];
Thus, I'm hoping to only allocate the memory for the objects actually needed, rather than all 1000 array objects immediately.
Am I interpreting this correctly? In other words, am I correct in my interpretation that the number of arrayed elements stated in the declaration is the MAXIMUM possible number of array elements, not how much memory is allocated at that moment? It this is correct, then theoretically, the declaration:
NSObject *myObject[10000];
Wouldn't pull any more memory than the declaration:
NSObject *myObject[5];
Can someone confirm that I'm understanding this process correctly, enlighten me if I've got this mixed up in my mind. :)
Thanks!
Why not use NSMutableArray? You can initWithCapacity or simply allocate with [NSMutableArray array]. It will grow and shrink as you add and remove objects. For example:
NSMutableArray *array = [NSMutableArray array];
NSObject *object = [[NSObject alloc] init];
[array addObject:object]; // array has one object
[array removeObjectAtIndex:0]; // array is back to 0 objects
// remember to relinquish ownership of your objects if you alloc them
// the NSMutable array was autoreleased but the NSObject was not
[object release];
Your understanding is mostly correct. When you do:
NSObject *myObject[1000];
You immediately allocate storage for 1000 pointers to NSObject instances. The NSObject instances themselves are not allocated until you do [[NSObject alloc] init].
However, doing NSObject *myObject[10000] will consume more space than doing NSObject *myObject[5], because 10,000 pointers certainly require more memory to represent than 5 pointers.
Remember that both things consume space, the pointer to the NSObject, and the NSObject instance itself, though in practice the space consumed by an NSObject instance will be significantly larger than the 4 bytes consumed by the pointer that refers to it.
Anyhow, perhaps more importantly, there is a better way to manage dynamic object allocation in Cocoa. Use the built-in NSMutableArray class. Like:
NSMutableArray* objects = [[NSMutableArray alloc] init];
[objects addObject: [[[NSObject alloc] init] autorelease]];

Does removing an object from NSArray automatically release its memory?

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.

What is the difference between arrayWithObjects and initWithObjects?

Can you please explain me exact difference between these two lines?
NSArray *foo = [NSArray arrayWithObjects:#"hai",#"how",#"are",#"you",nil];
NSArray *bar = [[NSArray alloc] initWithObjects:#"hai",#"how",#"are",#"you",nil];
arrayWithObjects is "convenience constructor".
It will do:
return [[[NSArray alloc] initWithObjects:#"hai",#"how",#"are",#"you",nil] autorelease]
for you.
It is just a convenience method to get an autoreleased object while improving the readability of the statement. Keep in mind that the fact that the object is autoreleased is a simple convention of the language (not a rule, so you could do differently, but I would not suggest that).
arrayWithObject returns an autoreleased array so you do not have to worry about releasing it when you don't need it anymore (but if you store it in an instance variable, you should retain it to prevent the autorelease pool from freeing it). initWithObject returns an array with a retain count of 1, i.e. you own the array and you must release it at some point to prevent memory leaks.
You might want to read this guide for more clarification.
You own the second array but not the first.

Objective C creating custom arrays

In other languages I could create a class then use this to create an array of objects in that class eg class price which is used in a performance class to define a price[] prices;
in objective C i cant get this to work, how do you do it?
The price class is an inherit of NSObject, can I use NSMutableArray?
If you have a class Price, and it inherits from NSObject, then you can have an array of them stored in an NSArray or NSMutableArray. You could also store them in a C array, or an STL vector, although the memorymanagement sematics may be difficult in those cases.
In the case of an NSArray/NSMutableArray, the array takes an ownership reference on the object, so you can release it after adding it to the array, and it will remain in memory until it is removed from the array (and all other locations).
Code might look like:
NSMutableArray* a = [NSMutableArray array];
[a addObject:[Price price]];
// and/or
[a addObject:[[[Price alloc] init] autorelease];
// and/or
Price* p = [[Price alloc] init];
[a addObject:p];
[p release];
NSLog( #"The array is %#", a );
// Remember at this point you do not "own" a, retain it if you want to keep it, or use [NSMutableArray new] above
When a is released, all the Price objects it contains will be released (and potentially deallocated).
Yes, NSMutableArray is what you would want to use.
To answer your last question first: if you are storing instances of Objective-C object (which, as you say, inherit from NSObject) then yes, use NSMutableArray. However, this won't work for primitive types (like int, BOOL, char, char*, etc.).
Objective-C uses the C way of declaring arrays with one caveat: you can't allocate memory on the stack (which is what that does in C), only on the heap. That means you have to use malloc (prefer NSAllocateCollectable() on Leopard or later) and free to manage the memory. Also, you declare the array as a pointer to an array or pointers. Something like this: (Note: pulled from thin air, untested.)
Price **prices = malloc(numberOfEntries * sizeof(Price*));
...
free(prices);
Using an NSMutableArray is generally much easier than managing your own arrays. Just be aware of the memory management rules: collections call -retain on an object when it is inserted, and -release on it when it is removed (or on all objects if the collection is deallocated).