views:

112

answers:

1

Currently I am using NSMutableArray as a property. However I am also using opengl and for performance purposes I want to use malloc to create an a pointer to the int array and have this as the property.

How would I do this in objective c and still make sure that my memory is safe? Perhaps this is not even a safe thing to do in objective c? Mixing malloc with properties.

+4  A: 

You can have pointers as properties. You're going to have to manage the memory yourself though, (ie since it won't be an objective c object, it can't be automatically retained and release.)

The following should work.

@interface ClassWithProperties : NSObject {
    int *pointer;
}

@property int *pointer;

@end


@implementation ClassWithProperties

@synthesize pointer;

- (void) initializePointer {
    self.pointer = malloc(sizeof(int) * 8);
}

- (void) dealloc {
    free(self.pointer);
}

@end
Tom
I recommend a `(nonatomic)` (removes threading overhead) after `@property` and a `if (self.pointer != NULL)` in front of `free(self.pointer)`.
MrMage
You don't need the `if(self.pointer != NULL)` check before `free()`, `free()` is required by the C standard to have no effect if the pointer passed to it is NULL.
Adam Rosenfield