我玩 iPhone 开发已经有一段时间了,虽然当你是一个“硬核”.NET 开发人员时感觉有点尴尬,但一旦你习惯了它并没有那么糟糕。
在我读过的关于 Objective-C 的每一本书中,都只讨论了用于内存管理的 retain
/release
(引用计数)。作为一个老派的 C/C++ 开发人员,使用 malloc()
和 free()
的“正常”方式分配似乎很奇怪,仅在一些脚注中提及。
我知道 malloc()
和 free()
在 Objective-C 中工作,但我很好奇这是否是常见做法。毕竟,如果我想分配一个 100 个整数的数组,似乎这是最有效的方法:
int *array = malloc(sizeof(int) * 100);
memset(array,0,sizeof(int) * 100);
// use the array
free(array);
这确实是最好的方法,还是我应该避免使用普通的 C 内存管理?
最佳答案
有一个围绕原始内存的 Objective-C 包装器,我喜欢将它用于类似的任务:NSMutableData
。它的好处是为您提供保留/释放所有权,而且它可以轻松扩展数组(无需您自己进行重新分配)。
您的代码如下所示:
NSMutableData* data = [NSMutableData dataWithLength:sizeof(int) * 100];
int* array = [data mutableBytes];
// memory is already zeroed
// use the array
// decide later that we need more space:
[data setLength:sizeof(int) * 200];
array = [data mutableBytes]; // re-fetch pointer in case memory needed to be copied
// no need to free
// (it's done when the autoreleased object is deallocated)
关于c - 在 Objective-C/iPhone 应用程序中使用 "classic"malloc()/free() 可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1150650/