【发布时间】:2012-08-07 20:24:00
【问题描述】:
我不确定用 10 个 MyClass 类型的固定大小的对象来声明我的数组的方法,以及这些不同的替代方案对效率、易于编码或其他方面的影响。
...牢记 xCode4.4 的新功能,尤其是:
- 对于 NSArray 和 NSDictionary 类,支持 Objective-C 文字。
- Objective-C 支持使用 '[ ]' 语法进行下标 容器对象。
...当然还有使用 ARC
特别是我需要编写返回这些数组作为结果的构造方法。
替代1
MyClass* objectOfMyClass;
MyClass* array1[10];
array1[5] = objectOfMyClass;
方法声明:
- (MyClass*[]) createArray { <--- is this declaration correct like this ?
ps。 AFAIK 这些数组放在堆栈内存中 - 但我不确定!
替代方案2
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 这些数组放在主内存中 - 不是堆栈 - 但我不确定!
替代方案3
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 {
非常感谢您为我们带来光明!
【问题讨论】: