Question

I am new to iOS so trying to understand memory management.

I have a .h File which contains a property and i want to use that var in some function.

@property (nonatomic, retain) NSMutableArray *myArray;

then in my .m File i have some function x.

-(void) x
{
     // How to allocate memory to the property variable  ??

     _myArray = [NSMutableArray alloc]init];
OR
     myArray= [[NSMutableAraay alloc]init]


 // what is the utility of "_" here ?
}

and how to manage memory in this case as we have already used keyword Retain in .h file and also allocated memory in func x then how to do memory management.

In dealloc method

-(void)dealloc
{
[myArray release];
OR
[_myArray release];
// same here whats the difference B/W 2.?
[super dealloc];
}
Was it helpful?

Solution

Using @property and @synthesize creates two methods, called accessors, that set and get a backing instance variable. The accessors are called either through normal method calls or dot notation (self.propertyname). The accessors offer a place to perform memory management or other tasks, which can be controlled to an extent in @synthesized accessors through the use of nonatomic/copy/etc. You can still directly access the instance variable a property masks by using the instance variable's name instead of self.propertyName. By default, the instance variable's name is the property's name preceded by an underscore. The underscore prevents people from accidentally directly accessing the instance variable when they don't mean to and can prevent namespace collisions. You can also implement your own accessors.

self.myArray //goes through the setter/getter of the property
_myArray     //directly accesses backing instance variable while ignoring accessors
myArray      //incorrect

Note that the name of the backing instance variable can be changed using @synthesize myPropertyName = myCoolName.

In terms of usage, in most cases you would use self.thing. The exception would be custom setters/getters (ex. return _thing) and dealloc where you would use [_thing release] to counter the retain that was sent to the object when it passed through the retain-style setter. The reason for not calling the accessor within the accessor should be obvious. We don't use the accessor in dealloc to prevent unwanted effects.

EDIT: Here's some nice resources to help you better understand manual reference counting.

  1. Understanding reference counting with Cocoa and Objective-C
  2. Memory Management Programming Guide (from Apple)

Also, if you want to develop for iOS consider using ARC. ARC stands for Automatic Reference Counting. Unlike MRC (Manual Reference Counting) where you explicitly add retain and release calls to your code, ARC conservatively handles reference counting for you, retaining and releasing objects as it sees fit. You can read about ARC below.

  1. Transitioning to ARC (from Apple)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top