简体   繁体   中英

How to dynamically allocate array of pointers to objects in Objective-C?

I'm trying to improve performance for my application, and I'd like to change from the NSMutableArray I'm currently using to a dynamically allocated C array.

As a test, I've created this class:

In my class interface, I have:

MyObject *myObjectArray;

In my implementation, after the object has been initialised, I have another method to set up the array:

-(void) createObjectsWithNumberOfObjects:(int)numberOfObjects
{
    MyObject *tempObject = nil;
    myObjectArray = (MyObject*) malloc(numberOfObjects * sizeof(tempObject));
    for( int i = 0; i < numberOfObjects; i++ )
        tempObject = [[MyObject alloc] init];
        myObjectArray[i] = (MyObject*) tempObject; // error
    }
}

I'm getting an error of: Incompatible Types In Assignment

So what am I doing wrong?

Is using a dynamically allocated array of objects like this possible?

Also, In my dealloc method, I have it setup to call release on each object then free(myObjectArray)

You need some more * s. Declare your array pointer as:

MyObject **myObjectArray;

And then initialize it like this:

myObjectArray = (MyObject**) malloc(numberOfObjects * sizeof(MyObject *));

Leave everything else in your code the same as it is now and you should be good! Why do you want to change from NSMutableArray ? It's a lot more capable in terms of flexibility and Cocoa support than your C array will be.

Are you really sure you will improve performance much? NSMutableArray has been around a long time and is likely to be more intelligent than you at this point in terms of allocating more memory for new elements.

Now if you were creating a linked list or something, that could yield a benefit for things like inserts in the middle... but for just a plain array you can add on to, I'm not sure how much gain you will see.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM