PDA

View Full Version : Question on initializing variable




blindjesse
Nov 19, 2009, 11:43 PM
I haven't found a good answer to this question in the relevant documents, but this seems to be a rudimentary thing, so I wonder if I'm missing it somewhere.

Consider this code:


@interface

class Myclass: NSObject{
SomeClass *someObject;
}

@property (nonatomic, retain) SomeClass *someObject;
@end


@implementation

@synthesize someObject;

...

@end


Now consider initializing that string somewhere. Often in code I've seen, the standard way is this:



....
SomeClass *anObject = [[SomeClass alloc] init];
self.someObject = anObject;
[anObject release];



My question is, why not just do this?


self.someObject = [[SomeClass alloc] init];


And then release it in the class' dealloc procedure.

Thanks



admanimal
Nov 20, 2009, 01:02 AM
When you alloc and init SomeClass, its retain count is set to 1. Since the someObject property is defined to also retain the object, doing


self.someObject = [[SomeClass alloc] init]


results in a retain count of 2 for the object that you have just created, one from alloc/init and one from assigning it via the retained property. Therefore if you just release it in the dealloc method of the class, it will still have a retain count of 1 and will cause a memory leak.

North Bronson
Nov 20, 2009, 01:57 AM
You could also just access the instance variable directly:

someObject = [[SomeClass alloc] init];

Since this isn't calling your setter, you will not be sending a retain message to the new object.

For an object-oriented purist, you tend to avoid accessing your instance variables directly and relying more on your getters and setters. But to simply initialize your object, go ahead and access the variable directly.

blindjesse
Nov 20, 2009, 09:05 AM
Thanks, this makes good sense.

admanimal
Nov 20, 2009, 10:04 AM
You could also just access the instance variable directly:

someObject = [[SomeClass alloc] init];

Since this isn't calling your setter, you will not be sending a retain message to the new object.

For an object-oriented purist, you tend to avoid accessing your instance variables directly and relying more on your getters and setters. But to simply initialize your object, go ahead and access the variable directly.

Of course technically this is fine to do if it really is the first time someObject is being set, but it's not a good habit to get into since if someObject -had- already been set, this code would also cause a memory leak, unless you manually release its previous value.

North Bronson
Nov 20, 2009, 01:41 PM
You're right. Maybe try:

if (someObject == nil)
{
someObject = [[SomeClass alloc] init];
}

which is also a good way to initialize your instance variables lazily.