简体   繁体   中英

What is the difference between these two ways of allocating memory in Objective-C?

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];

or

   NSMutableDictionary *alpha = [NSMutableDictionary dictionary];

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];

is exactly the same thing as:

[[[NSMutableDictionary alloc] init] autorelease];

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.

The convention is:

  1. If you see init , new or copy : it's a retained object.
  2. If the method name starts with the class name (sans the framework prefix), it's an autoreleased object.

[NSMutableDictionary dictionary] is a class method on the NSMutableDictionary class. It contains the calls to alloc and init , just as you would do them manually. Due to this being a very commonly used class, its author included this so called "factory method" to make life easier for users of his/her class.

See http://en.wikipedia.org/wiki/Factory_method_pattern for more details on this pattern.

As for which is good practice, IMHO you should use the factory method. It makes your own code more readable and saves you typing. Moreover - although I am not sure if this is the case with NSMutableDictionary - using the factory method makes maintenance easier for both its developers and yourself, because they are eg free to change the concrete subclass implementation you will receive from the factory, without having you change your application code.

As correctly pointed out it the comments, factory methods like this return autoreleased instances of objects, so if you only use them locally in a method, there is no need to worry about them from a memory management point of view. For more details on memory management, autorelease and the new ARC runtime with automatic reference counting, you should deep dive into Apple's documentation on the topic, if you haven't already.

这两行都将为alpha分配内存,不同之处在于第二个alpha是自动释放对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM