ios - Am I correctly creating and passing this C array to Objective-C method and referencing it with a property? -
i created c array this:
unsigned char colorcomps[] = {2, 3, 22, 55, 9, 1};
which want pass initializer of objective-c object.
so think have put array on heap:
size_t arraybytesize = numcolorcompvals * sizeof(unsigned char); unsigned char *colorcompsheap = (unsigned char*)malloc(arraybytesize);
then have write first "stack memory array" heap array in loop:
for (int = 0; < numcolorcompvals; i++) { colorcompsheap[i] = colorcomps[i]; }
side question: there more elegant solution avoid for-loop step?
and pass method:
defined as
- (id)initwithcolorcompsc:(unsigned char *)colorcompsheap; theobject *obj = [[theobject alloc] initwithcolorcompsc:colorcompsheap];
theobject
has property hold c-array:
@property (nonatomic, assign) unsigned char *colorcomps;
and in -dealloc free it:
free(_colorcomps);
this in theory. use arc objective-c. am doing correct or there better way?
if theobject
going free array, init
method should 1 make copy, not caller. way each instance of theobject
make own copy , frees own copy, owns copy.
also, doesn't matter parameter init comes from, stack or heap. won't matter if init
method makes copy of it.
use memcpy make copy, sizeof
destination array, .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 first element (in case // element type changed later, still works right) size_t arraysize = sizeof(colorcomps[0]) * numberofcolorcomps; _colorcomps = malloc(arraysize); memcpy(_colorcomps, colorcomps, arraysize); } return self; } @end
Comments
Post a Comment