Memory allocation for an array of objects. Is my understanding valid?

I have a question about memory allocation for objects in an array. I am looking to create an array of objects, but at compile time I do not know how many objects I need, and therefore do not want to reserve more memory than I need.

What I would like to do is allocate memory as needed. The way I would like to do this is when the user clicks the Add button, the array grows by one additional object and the necessary memory is allocated for the new object.

In my beginning understanding of Objective-C (I was a professional programmer about 20 years ago and only recently started writing code again), I came up with the following code segments:

First I declared my object:

    NSObject *myObject[1000]; // a maximum number of objects.

Then, when the user clicks the Add button, he starts the method with the selection code: (note: the variable I starts with the value 1 and increases each time the Add button is clicked)

    ++i
    myObject[i] = [[NSObject alloc] init];

Thus, I hope only to allocate memory for the actually necessary objects, and not all 1000 objects of the array.

Am I interpreting this correctly? In other words, can I correct in my interpretation that the number of array elements specified in the declaration is MAXIMUM the possible number of array elements, and not how much memory is allocated at this moment? This is correct and then theoretically expression:

    NSObject *myObject[10000];

There will be no more memory than a declaration:

    NSObject *myObject[5];

Can someone confirm that I understand this process correctly, enlighten me if I had this in my head. :)

Thank!

+3
2

NSMutableArray? initWithCapacity [NSMutableArray array]. . :

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]; 
+4

. :

NSObject *myObject[1000];

1000 NSObject. NSObject , [[NSObject alloc] init].

NSObject *myObject[10000] , NSObject *myObject[5], 10 000 , , , 5 .

, , NSObject NSObject, , NSObject, , 4 , .

, , , Cocoa. NSMutableArray. :

NSMutableArray* objects = [[NSMutableArray alloc] init];
[objects addObject: [[[NSObject alloc] init] autorelease]];
+3

All Articles