可以使用“经典"吗?Objective-C/iPhone 应用程序中的 malloc()/free()? [英] Is it ok to use "classic" malloc()/free() in Objective-C/iPhone apps?

查看:20
本文介绍了可以使用“经典"吗?Objective-C/iPhone 应用程序中的 malloc()/free()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经玩了一段时间的 iPhone 开发了,虽然当你是一个核心".NET 开发者时感觉有点尴尬,但一旦你习惯了它并没有那么糟糕.

I've been playing around with iPhone development for a while, and although it feels a bit awkward when you're a "hard core" .NET developer, it's not all that bad once you get used to it.

在我读到的关于 Objective-C 的每本书中,都只讨论了用于内存管理的 retain/release(引用计数).作为一个老牌 C/C++ 开发人员,使用 malloc()free() 分配正常"方式似乎很奇怪,只是在一些脚注中提到.

In every book I read about Objective-C, there's only talk about retain/release (reference counting) for memory management. As an old-skool C/C++ developer, it seems strange that allocating the "normal" way, using malloc() and free() is only mentioned in some footnotes.

我知道 malloc()free() 在 Objective-C 中工作,但我很好奇这是否是普遍做法.毕竟,如果我想分配一个 100 个整数的数组,这似乎是最有效的方法:

I know that malloc() and free() work in Objective-C, but I'm curious if it is common practice or not. After all, if I want to allocate an array of 100 integers, it seems that this is the most efficient way to do it:

int *array = malloc(sizeof(int) * 100);

memset(array,0,sizeof(int) * 100);

// use the array

free(array);

这确实是最好的方法,还是应该避免简单的 C 内存管理?

Is this indeed the best way, or should I avoid plain C memory management?

推荐答案

有一个围绕原始内存的 Objective-C 包装器,我喜欢将其用于类似任务:NSMutableData.它的好处是可以让您保留/释放所有权,而且可以轻松扩展数组(无需您自己重新分配).

There's an Objective-C wrapper around raw memory which I like to use a lot for similar tasks: NSMutableData. It has the benefit of giving you retain/release ownership plus it can grow the array easily (without having you to do the realloc yourself).

您的代码如下所示:

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)

这篇关于可以使用“经典"吗?Objective-C/iPhone 应用程序中的 malloc()/free()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆