我不确定如何声明具有固定大小的MyClass类型的10个对象的数组,以及这些不同的替代方案对效率、代码易用性或其他方面有什么影响。
...keeping记住了新的xCode4.4特性,特别是:
当然,...and使用ARC
特别是,我需要编写构造器方法,从而返回这些数组。
Alternative1
MyClass* objectOfMyClass;
MyClass* array1[10];
array1[5] = objectOfMyClass;方法声明:
- (MyClass*[]) createArray { <--- is this declaration correct like this ?ps。AFAIK这些数组放在堆栈内存中--但我不确定!
Alternative2
MyClass* objectOfMyClass;
NSMutableArray *array2 = [[NSMutableArray alloc] init];
for (int i = 0; i<10; i++)
[array2 addObject:objectOfMyClass]; //objects get added in some way...
//can't directly access nTh object in this case, need to add from 0 to 9
//conversion to non mutable array, since size will not change anymore
NSArray *array3 = [NSArray arrayWithArray:array2]; 方法声明:
- (NSArray*) createArray {ps。AFAIK这些数组放在主内存中--不是堆栈--但我不确定!
Alternative3
NSArray *array4 = [[NSArray alloc] init];
array4 = ...how to prepare the array so it can hold 10 objects without using NSMutableArray ?
otherwise I do not see a difference to alternative 2...
for (int i = 0; i<10; i++)
array4[i] = objectOfMyClass];方法声明:
- (NSArray*) createArray {非常感谢你给我们带来了光明!
发布于 2012-08-07 21:01:28
有一篇很棒的关于文字这里的文章。你不能做第一种选择。最好的方法是:
NSMutableArray *holdsMyClass = [NSMutableArray arrayWithCapacity:10]; // sized so array does not need to realloc as you add stuff to it不能通过索引过大小来任意增加数组的大小--如果在索引5处有一个对象,则可以替换它:
holdsMyClass[5] = obj;例如,如果您试图编译它,它将失败:
- (NSArray*[]) createArray
{
NSArray *foo[10];
foo[2] = [NSArray array];
return foo;
}生成此错误:“数组初始化程序必须是初始化程序列表”
https://stackoverflow.com/questions/11853558
复制相似问题