Objective-C:@property中的C结构,带有自定义释放功能

时间:2015-04-04 07:21:30

标签: ios objective-c c memory-management struct

我有一个带有自定义分配/释放函数的C结构,因为该结构具有动态分配的嵌套数组:

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);
}

我想在Objective-C应用程序的UIViewController中使用此结构。网格的寿命应该与控制器的寿命相同。

如果它是C ++对象,我会在构造函数中调用AllocGrid()并将其与析构函数中的FreeGrid()调用相匹配。所以我尝试将分配放在init消息和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

但是从未执行分配,在iOS模拟器中运行应用程序时,我看不到“dealloc”日志消息。我想我可以在viewDidLoad进行分配,但我觉得这不是正确的做法。因此我的问题是:

问题:如何在@property中包装C结构并强制它使用我的自定义AllocGrid()DeallocGrid()函数?
或者:在Objective-C中是否有等价的scoped_ptr?或者我应该推出自己的?

1 个答案:

答案 0 :(得分:2)

我认为将分配放在viewDidLoad()中是正确的。实际上,讨论了为什么init()未在ViewController中调用iPhone UIViewController init method not being called。但是,这取决于你的背景,如果你想初始化你的结构"之前"视图出现后,您应该将初始化放在viewWillAppear中。还有另一个有趣的线程在讨论ViewController中的调用顺序Order of UIViewController initialization and loading。最后,我想指出Objective-C是C的扩展,所以"基本"分配/自由行为应该是相同的。