0

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?

Julien-L
  • 5,267
  • 3
  • 34
  • 51
  • 2
    `-init` is not the designated initializer for `UIViewController`: [iPhone UIViewController init method not being called](http://stackoverflow.com/q/772182) – jscs Apr 04 '15 at 07:58

1 Answers1

2

I think putting the allocation in the viewDidLoad() is correct. In fact, there is a discussion regarding to why init() is not being called in ViewController, iPhone UIViewController init method not being called. But, it depends on your context, if you want to initialize your structure "before" the view appear, you should put your initialization in viewWillAppear. There's another interesting thread talking about the invoking order in ViewController, Order of UIViewController initialization and loading. Finally, I want to point out Objective-C is an extension of C, so the "basic" allocation/free behavior should be the same.

Community
  • 1
  • 1
TimeString
  • 1,778
  • 14
  • 25