viewDidLoad 中完成时,动态内存分配存在问题,例如数组的 malloccalloc . 使用 NSMutableData 替换malloc时出现同样的问题here . 我不需要解决方案,因为我将提出自己的解决方案,但欢迎讨论,以便更深入地了解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...