Befor understand the NSAutoreleasePool let us take a look about some concept regarding to Memory Management.
Release & Autorelease?
Release and Autorelease are the terms related to the Memory Management.
whenever you own a object its your responsibility to release it .
If you don’t release your own a object properly Objective -C cannot reclaim it for the use of other objects and there will be a memory leak.
If you are not sure about releasing that object, please make sure you do autorelease.
The concept of an autorelease pool is simple whenever an object instance is marked as autoreleased it will have a retain count of +1 at that moment in time,
Syntax of NSAutoreleasePool
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
but at the end of the run loop the pool is drained, and any object marked autorelease then has its retain count decremented.
Creating a new object
Creating a new object in Objective-C is usually a two-step process.
- Allocation : Memory has to be allocated for the object alloc
- Initializtion : The object is initialized with proper values. init
Alloc class method test a chunk of memory to hold the object, and returns the pointer.
MyClass * myObj = [MyClass alloc];
- However, that object is not quite ready to use yet
- It has to be initialized first (otherwise strange bugs are mostly guaranteed).
- This is accomplished by the init instance method, which is often overridden.
- These methods return an object of type id the same object that is being initialized.
- It is important that you nest the alloc and init methods
- There are instances where the initialization method may not return the same object as was allocated.
- This is true when working with classes such as NSString, which are in fact a public interface for a variety of classes.
- These cases, the initialization method may choose to return an object that is not quite the originally requested class;
MyClass *myObj = [[MyClass alloc] init];