What's the magic of NSAutoreleasePool in Objective-C/cocoa framework?

10,380

Solution 1

Q1: The magic is that NSObject -autorelease instance method calls NSAutoreleasePool +addObject: class method. The NSObject instance is pooled in the current NSAutoreleasePool instance. And NSAutoreleasePool -drain instance method calls release method of pooled instances.

It is not the exactly same between Cocoa implementation of Apple and GNUstep, but it is similar.

I'm not sure why month is not released, it should be release by drain.

Q2: You can use NSAutoreleasePool wherever you want to use at. Instantiate a NSAutoreleasePool means the current pool will be changed by the new instance. drain will go back the current pool to the previous instance.

Besides NSApplicationMain never returns. It calls the exit function to exit the application and terminate the process.

Solution 2

Q1:

You don't need to release the month instance in the example you give because the NSArray class method you're calling (arrayWithObjects:) returns an instance that is autoreleased. By convention in Cocoa, class methods that start with the name of the class will return autoreleased instances of that class. These examples:

[NSString stringWithFormat:@"Holla %@", @"back girl!", nil];
[NSArray arrayWithObjects:@"Holla", @"back", @"girl!", nil];

Will both return instances of their respective objects that are autoreleased.

Share:
10,380
prosseek
Author by

prosseek

A software engineer/programmer/researcher/professor who loves everything about software building. Programming Language: C/C++, D, Java/Groovy/Scala, C#, Objective-C, Python, Ruby, Lisp, Prolog, SQL, Smalltalk, Haskell, F#, OCaml, Erlang/Elixir, Forth, Rebol/Red Programming Tools and environments: Emacs, Eclipse, TextMate, JVM, .NET Programming Methodology: Refactoring, Design Patterns, Agile, eXtreme Computer Science: Algorithm, Compiler, Artificial Intelligence

Updated on October 23, 2022

Comments

  • prosseek
    prosseek over 1 year

    I found an example of Objective-C/cocoa framework has the following code.

    int main()
    {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
        // Create an array
        NSArray *month = [NSArray arrayWithObjects:@ ... nill];
    
        [pool drain];
    }
    
    • Q1 : What's the magic behind this (Why do I need to have the NSAutoreleasePool code?)? What magic is happening between the NSAutoreleasePool and pool drain block? I see I don't need to release*month myself. Is this because it's inside the NSAutoreleasePool and pool drain block?

    • Q2 : With Xcode, I'm already given the main() function. In this case, how can I use the NSAutoreleasePool and pool drain?

    For example :

    int main(int argc, char *argv[])
    {
        //NSAutoreleasePool *pool = [[[NSAutoreleasePool] alloc] init];
        return NSApplicationMain(argc,  (const char **) argv);
    }