【问题标题】:Objective-C: C struct in @property with custom deallocation functionObjective-C:@property 中的 C 结构,具有自定义释放功能
【发布时间】: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 等效的内容?还是我应该推出自己的?

【问题讨论】:

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


【解决方案1】:

我认为将分配放在viewDidLoad() 中是正确的。事实上,关于为什么 init() 没有在 ViewController 中被调用的讨论,iPhone UIViewController init method not being called。但是,这取决于你的上下文,如果你想在视图出现之前初始化你的结构,你应该把你的初始化放在viewWillAppear。还有另一个有趣的线程在讨论 ViewController 中的调用顺序,Order of UIViewController initialization and loading。最后,我想指出 Objective-C 是 C 的扩展,所以“基本”的分配/释放行为应该是一样的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 2013-07-14
    相关资源
    最近更新 更多