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

后端 未结 3 565
时光说笑
时光说笑 2020-12-07 04:41

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:

           


        
3条回答
  •  既然无缘
    2020-12-07 05:13

    [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.

提交回复
热议问题