Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an Objective-C command line program require an NSAutoreleasePool?

Tags:

objective-c

I'm learning Objective-C by playing around with some code in a simple command line program, here's my code:

#import <Foundation/Foundation.h>
#import <stdio.h>

int main(int argc, char** argv)
{
    NSString *hello = @"hello world";

    printf("msg: %s\n", [hello UTF8String]);

    return 0;
}

I compile and run it like this:

gcc test.m -o test -ObjC -framework Foundation
./test

and get the following output:

2011-06-08 20:35:21.178 test[10220:903] *** __NSAutoreleaseNoPool(): Object 
0x10010c8b0 of class NSCFData autoreleased with no pool in place - just leaking
msg: hello world

So I can see that the error is referring to the fact that there's no NSAutoreleasePool, and when I add one, the error goes away:

#import <Foundation/Foundation.h>
#import <stdio.h>

int main(int argc, char** argv)
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSString *hello = @"hello world";

    printf("msg: %s\n", [hello UTF8String]);

    [pool release];

    return 0;
}

So am I right in assuming that a command line application that uses objects like NSString etc. and compiles against Foundation requires an auto release pool to be created manually? And is my example above the best way of doing it?

Note: I also tried to [hello release]; without the NSAutoreleasePool to see if I could just manually clear up the memory without using a pool, but got the same problem.

like image 375
Martin Avatar asked Jun 08 '11 19:06

Martin


People also ask

What is Nsautoreleasepool Objective C?

An object that supports Cocoa's reference-counted memory management system.

What is Autorelease pool in Swift?

The autoreleasepool allows you to explicitly manage when autorelease objects are deallocated in Swift, just like you were able to in Objective-C. Note: When dealing with Swift native objects, you generally will not receive autorelease objects.


1 Answers

Yes, and yes.

Cocoa (in GUI or Foundation form) expects an autorelease pool to be present; the internals of the framework (not just your own code) make liberal use of the -autorelease message and the pools, and if you don't have any pools on the autorelease pool stack, it'll complain, and leak the objects, as you've seen.

I presume you have garbage collection turned off; I've never developed with it on, but in that case I could imagine you wouldn't need this.

Update Autorelease pools can now be created using an @autoreleasepool {...} block, which has the same effect, and some nice bonuses like the ability to just jump/return out of it.

like image 76
Ben Zotto Avatar answered Sep 26 '22 00:09

Ben Zotto