I have a C struct with custom allocation/deallocation functions because the struct has a dynamically-allocated nested array:
struct Cell {
int data, moreData;
};
struct Grid {
int nrows, ncols;
struct Cell* array;
};
struct Grid* AllocGrid (int nrows, int ncols) {
struct Grid* ptr = (struct Grid*) malloc (...);
// ...
ptr->array = (struct Cell*) malloc (...);
return ptr;
}
void FreeGrid (struct Grid* ptr) {
free (ptr->array);
free (ptr);
}
I want to use this struct in the UIViewController
of my Objective-C app. The grid's lifespan should be the same as the controller's one.
If it were a C++ object, I would call AllocGrid()
in the constructor and match it with a call to FreeGrid()
in the destructor. So I tried to put the allocation in the init
message and the deallocation in dealloc
:
@implementation ViewController
{
struct Grid* theGrid;
}
- (id)init {
self = [super init];
if (self) {
NSLog(@"init()");
theGrid = AllocGrid(10,10);
}
return self;
}
- (void)dealloc {
NSLog(@"dealloc()");
DeallocGrid(theGrid);
theGrid = NULL;
}
@end
But the allocation is never executed and I cannot see the "dealloc" log message when running the app in the iOS simulator. I guess I could do the allocation in viewDidLoad
but I feel it's not the right thing to do. Hence my question:
Question: How can I wrap the C struct in a @property
and force it to use my custom AllocGrid()
and DeallocGrid()
functions?
Or: Is there an equivalent of a scoped_ptr
in Objective-C? Or should I roll out my own?