我试图在 Objective-C 中实现一个 n x n 多维整数数组,因为使用 NSMutableArray 似乎开销太大,我决定只使用 C 的 malloc 和 free 来实现它。我的问题是,下面的代码在 ARC Objective-C 下是否正确(没有内存泄漏)?
@interface TwoDimensionalArray
{
int **array;
int size;
}
@end
@implementation TwoDimensionalArray
- (id)initWithSize: (int)s
{
if(self = [super init])
{
size = s;
array = malloc(sizeof(int*) * size);
for(int i = 0; i < size; i++)
{
array[i] = malloc(sizeof(int) * size);
for (int j = 0; j < size; j++)
{
array[i][j] = 0;
}
}
}
return self
}
- (id)init
{
return [self initWithSize:1];
}
- (void)dealloc
{
for(int i = 0; i < size; i++)
{
free(array[i]);
array[i] = nil;
}
free(array);
array = nil;
}
@end
如果这不正确,或者如果你认为在 Objective-C 中有更好的方法而不用 mallocs,请告诉我。谢谢。
最佳答案
ARC 为Objective-C 对象 和 block 实现了自动内存管理,但不 自动化 malloc/free。 (引用:Clang/ARC documentation: General, ARC Release Notes: FAQ .)
所以您的问题与 ARC 无关:malloc()
必须是
free()
'd(dealloc
是这样做的好地方)。乍一看,您的代码看起来不错。
(小提示:在dealloc
中清零数组指针不是必须的,但是
NULL
将是要分配的适当指针值,nil
用于 Objective-C 对象。)
我不知道使用 NSMutableArray
这样的 Objective-C 集合有多少开销
会导致,应该通过分析来测试(如评论中所述)。
关于objective-c - ARC Objective-C 中的 C 风格多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16168923/