简体   繁体   English

如何在Objective-C中动态分配指向对象的指针数组?

[英]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. 我正在尝试提高应用程序的性能,并且希望将当前使用的NSMutableArray更改为动态分配的C数组。

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) 另外,在我的dealloc方法中,我将其设置为在每个对象上调用release,然后释放(myObjectArray)

You need some more * s. 您需要更多* 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 ? 为什么要从NSMutableArray更改? It's a lot more capable in terms of flexibility and Cocoa support than your C array will be. 在灵活性和可可支持方面,它比C阵列要强大得多。

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. NSMutableArray已有很长时间了,就为新元素分配更多的内存而言,NSMutableArray可能会比您现在更聪明。

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. 现在,如果您正在创建一个链表或其他内容,则可以为中间插入之类的东西带来好处……但是对于可以添加到其中的纯数组,我不确定会看到多少收益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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