这两种在Objective-C中分配内存的方法有什么区别? [英] What is the difference between these two ways of allocating memory in Objective-C?
问题描述
我对在Objective-C中分配内存的正确方法感到困惑。假设我有一个NSMutableDictionary。我可以通过两种方式初始化它:
I am confused about the proper means of allocating memory in Objective-C. Suppose I have an NSMutableDictionary. There are two ways I can initialize it:
NSMutableDictionary *alpha = [[NSMutableDictionary alloc] init];
或
NSMutableDictionary *alpha = [NSMutableDictionary dictionary];
它们之间有什么区别?我知道第一个为alpha分配内存,但是第二个呢?
What is the difference between them? I know the first allocates memory for alpha, but what about the second?
建议哪一个作为分配内存的最佳做法?
Which of these is recommended as the best practice for allocating memory?
推荐答案
[NSMutableDictionary dictionary];
与以下内容完全相同:
[[[NSMutableDictionary alloc] init] autorelease];
它只会为您节省一些打字费用。只要您知道保留对象和自动释放对象之间的区别,使用哪一个并不重要。如果您正在使用ARC,那么您甚至不需要知道。
It just saves you some typing. It doesn't matter which one you use, as long as you know the difference between a retained object and an autoreleased one. If you're using ARC, then you don't even need to know that.
约定是:
- 如果你看到 init ,新或复制:它是一个保留对象。
- 如果方法名称以类名开头(没有框架前缀),则它是一个自动释放的对象。
- If you see init, new or copy: it's a retained object.
- If the method name starts with the class name (sans the framework prefix), it's an autoreleased object.
这篇关于这两种在Objective-C中分配内存的方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!