【发布时间】:2015-04-04 07:21:29
【问题描述】:
我有一个带有自定义分配/释放函数的 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 中进行分配,但我觉得这不是正确的做法。因此我的问题是:
问题:如何将 C 结构体包装在 @property 中并强制它使用我的自定义 AllocGrid() 和 DeallocGrid() 函数?
或者:Objective-C 中是否存在与 scoped_ptr 等效的内容?还是我应该推出自己的?
【问题讨论】:
-
-init不是UIViewController的指定初始化器:iPhone UIViewController init method not being called
标签: ios objective-c c memory-management struct