Saturday, April 27, 2013

NSAutoreleasePool example ios


The NSAutoreleasePool class is used to support Cocoa’s reference-counted memory management system. An autorelease pool stores objects that are sent a release message when the pool itself is drained.

Following code fragment shows a [NSAutoreleasePool example]

#import <Foundation/Foundation.h>

@interface OurObject: NSObject
-(void)dealloc;
@end

@implementation OurObject
-(void)dealloc
{
        printf("Dealloc on OurObject\n");
        [super dealloc];
}
@end

void createAPoolAndLeak()
{
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        OurObject *oo = [[OurObject alloc] init];

        // add to this function's pool...
        [oo autorelease];
        // ... and forget to release the pool! *Gasp*
}

void createAPoolAndDontLeak()
{
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        OurObject *oo = [[OurObject alloc] init];

        // add to this function's pool...
        [oo autorelease];
        // ... and release the pool!
        [pool release];
}

int main()
{
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

        printf("Creating a pool and not leaking...\n");
        createAPoolAndDontLeak();
        printf("Pool cleaned up.\n");
        printf("Creating a leaky pool\n");
        createAPoolAndLeak();
        printf("Leaky pool created.\n");

        printf("Releasing parent pool...\n");
        [pool release];

        printf("Pool is cleaned up...\n");
        return 0;
}