我是不是正确的创造和传递本C数组Objective-C的方法和属性引用它? [英] Am I correctly creating and passing this C array to Objective-C method and referencing it with a property?
问题描述
我创建一个C数组是这样的:
I created a C array like this:
unsigned char colorComps[] = {2, 3, 22, 55, 9, 1};
我想传递给一个Objective-C对象的初始化。
which I want to pass to an initializer of an Objective-C object.
所以,我认为我已经把阵列上的堆:
So I think I have to put the array on the heap:
size_t arrayByteSize = numColorCompVals * sizeof(unsigned char);
unsigned char *colorCompsHeap = (unsigned char*)malloc(arrayByteSize);
然后,我有我的第一个堆栈存储器阵列写入到阵列堆在for循环:
Then I have to write my first "stack memory array" to the heap array in for loop:
for (int i = 0; i < numColorCompVals; i++) {
colorCompsHeap[i] = colorComps[i];
}
侧问题:是否有一个更优雅的解决方案,以避免for循环步
然后我将它传递给方法:
And then I pass it to the method:
定义为
- (id)initWithColorCompsC:(unsigned char *)colorCompsHeap;
TheObject *obj = [[TheObject alloc] initWithColorCompsC:colorCompsHeap];
TheObject
有一个属性来保存C-数组:
TheObject
has a property to hold the C-array:
@property (nonatomic, assign) unsigned char *colorComps;
而在-dealloc我释放它:
And in -dealloc I free it:
free(_colorComps);
这是在理论上。我使用ARC的Objective-C的。 我这样做正确或是否有更好的办法?
This is in theory. I use ARC for Objective-C. Am I doing this correct or is there a better way?
推荐答案
如果 TheObject
将要释放的数组,那么它的的init
方法应该是一个使副本,而不是调用者。这样 TheObject
的每个实例做出自己的副本,并释放自己的副本,它的拥有的该副本。
If TheObject
is going to free the array, then its init
method should be the one to make the copy, NOT the caller. That way each instance of TheObject
make its own copy and frees its own copy, it owns that copy.
此外,然后不要紧其中参数到init来自于,栈或堆。如果的init
方法使得它的一个副本都不会有问题。
Also, then it doesn't matter where the parameter to the init comes from, stack or heap. It won't matter if the init
method makes a copy of it.
使用的memcpy,使复印件,与的sizeof
目标数组,喜欢本作的.m文件:
Use memcpy to make the copy, with sizeof
the destination array, like this for the .m file:
@interface PTTEST ()
@property (nonatomic, assign) unsigned char *colorComps;
@end
@implementation PTTEST
- (void)dealloc
{
free(_colorComps);
}
- (id)initWithColorCompsC:(unsigned char *)colorComps
numberOfColorComps:(unsigned)numberOfColorComps
{
self = [super init];
if (self) {
// compute size based on sizeof the first element (in case
// the element type get changed later, this still works right)
size_t arraySize = sizeof(colorComps[0]) * numberOfColorComps;
_colorComps = malloc(arraySize);
memcpy(_colorComps, colorComps, arraySize);
}
return self;
}
@end
这篇关于我是不是正确的创造和传递本C数组Objective-C的方法和属性引用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!