在viewDidLoad中使用malloc分配的iOS数组

时间:2014-10-02 22:21:49

标签: ios objective-c malloc viewdidload calloc

当在 viewDidLoad 中完成时,动态内存分配存在问题,例如数组的 malloc calloc 。用建议的here替换带有 NSMutableData 的malloc时遇到了同样的问题。我不需要解决方案,因为我将提出自己的解决方案,但欢迎讨论,以便更深入地了解iOS内存管理。我的代码包含以下部分:

在类扩展中,我定义了指针

@interface MyFirstViewController () {
   float* arrayPtr;
}

在viewDidLoad中,我使用malloc或calloc:

为数组分配了内存
arrayPtr = malloc(100 * sizeof(float));
NSAssert(arrayPtr != NULL, @"Could not allocate memory for an array.");

然后将指针传递给另一个objective-c类,该类将用数据填充数组。应用程序会随时崩溃。在不同的索引处丢失对数组的访问(都在适当的索引范围内)。它看起来好像数组已被释放。

我的解决方案: 仅在viewDidLoad

中将指针设置为NULL
arrayPtr = NULL;

在您需要数组的方法中,仅在第一次

时分配它
if (arrayPtr == NULL) {
   arrayPtr = calloc(100, sizeof(float));   // malloc is also working
   NSAssert(arrayPtr != NULL, @"Could not allocate memory for an array");
}
// use the pointer (array) here. Pass it to the other class as needed...

0 个答案:

没有答案
相关问题