Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

blindjesse

macrumors newbie
Original poster
Nov 19, 2009
3
0
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:

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:

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

My question is, why not just do this?

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

And then release it in the class' dealloc procedure.

Thanks
 
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

Code:
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.
 
You could also just access the instance variable directly:

Code:
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.
 
You could also just access the instance variable directly:

Code:
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.
 
You're right. Maybe try:

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

which is also a good way to initialize your instance variables lazily.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.