where should I alloc and release it?
Well, you'll allocate and release it the same place you do for any instance variable: in init
and dealloc
. The trick is that you have to use malloc
and free
instead of retain
and release
.
As for the properties, you can declare them, you'll just have to write your own accessors and mutators.
Also, recall that, for this purpose, a C array is like a pointer.
With that said, you might do something like this:
@interface MyClass : NSObject
{
int *arr;
}
@property int *arr;
@end
@implementation MyClass
#import <stdlib.h>
@dynamic arr;
- (id)init
{
if ((self = [super init])) {
arr = malloc(sizeof(int) * 256);
}
return self;
}
- (void)dealloc
{
free(arr);
[super dealloc];
}
- (int *)arr
{
// Return a copy -- don't want the caller to deallocate
// our instance variable, or alter it without our knowledge!
// Also note that this will leak unless the caller releases it.
int *arrCpy = malloc(sizeof(int) * 256);
memcpy(arrCpy, arr, sizeof(int) * 256);
return arrCpy;
}
- (void)setArr:(int *)anArr
{
if (arr != anArr) {
free(arr);
// Again, copy the data so that the caller can't
// change the values of specific ints without
// out knowledge.
int *anArrCpy = malloc(sizeof(int) * 256);
memcpy(anArrCpy, anArr, sizeof(int) * 256);
arr = anArrCpy;
}
}
There's some better error checking you could do, and the code could be prettied up a bit, but that's the gist.
You could also use CoreFoundation data types, which are basically just C primitives and structs; memory management would be a bit easier, but it's also not the "straight C" ints that you requested.
To be honest, though, I think you'd be better off just using an NSArray of NSNumber objects -- memory management would be far easier, and it'd probably be more compatible with other Objective-C frameworks. It would also be more platform independent, since Cocoa takes into account 64-bit vs. 32-bit environments, as well as endianness, with its data types. At the very least, you should probably use NSInteger instead of int.