目标C:堆栈与堆上的内存分配 [英] Objective C: Memory Allocation on stack vs. heap

查看:104
本文介绍了目标C:堆栈与堆上的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于何时在堆上分配事物(我需要释放它们)以及何时在堆栈上分配它们(我不需要释放它们),我有些困惑.

有一个经验法则吗?

我认为在C ++中,经验法则是,如果使用new关键字,则它们在堆上.目标c的规则是什么?我如何知道什么时候在堆栈上分配了东西?

这行代码会分配在堆栈上吗?

NSString *user = @"DEFAULT";

解决方案

在Objective-C中,这很容易:所有对象都分配在堆上.

规则是,如果您用名称中的allocnewcopy调用方法(或调用retain),则您拥有该对象,并且必须在以后的某个时候释放它完成后.关于这个主题已经写了很多.

您提供的示例是一个特例:这是一个静态字符串,我相信它实际上位于程序的数据段中(在堆上),但是它是静态的,因此您不必担心释放它. /p>

I am somewhat confused about when things are allocated on the heap (and I need to release them) and when they are allocated on the stack (and I don't need to relese them).

Is there a rule of thumb?

I think in C++ the rule of thumb is that if you use the new keyword they are on the heap. What is the rule with objective c? How can I tell when something is allocated on the stack?

Will this line of code be allocated on the stack?

NSString *user = @"DEFAULT";

解决方案

In Objective-C, it's easy: all objects are allocated on the heap.

The rule is, if you call a method with alloc or new or copy in the name (or you call retain), you own that object, and you must release it at some point later when you are done with it. There has been plenty written on the subject.

The example you give is a special case: that's a static string, I believe it is actually located in the program's data segment (on the heap), but it's static so you don't need to worry about releasing it.

这篇关于目标C:堆栈与堆上的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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