Reputation: 137
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)
Upvotes: 1
Views: 2833
Reputation: 75058
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.
Upvotes: 0
Reputation: 225032
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.
Upvotes: 2