Hey guys,
I'm a bit confused with certain uses of release and autorelease. I understand if you have something like:
NSString *string = [[NSString alloc] ...];
// create a label with string
[string release];
as it's a very simple case. However, when you start passing objects around, who takes responsibility to release them?
Let's take the following example:
MySuperLayer *superLayer = [[MySuperLayer alloc] init];
[self addChild:superLayer];
// repeat for superLayer2
MyClass1 *object1 = [MyClass1 createClassWithBla:bla];
[superLayer applyMyClass:object1];
[superLayer2 applyMyClass:object1];
[object1 release];
Let's assume that MySuperLayer is a custom class that inherits CCLayer. Let's also say that createClassWithBla is a class method that looks like:
+(id)createClassWithBla:(Bla*)bla
{
return [[self alloc] initWithBla:bla];
}
Let's also say that applyMyClass looks like:
-(void)applyMyClass:(MyClass*)aClass
{
if(myMyClass != nil) [myMyClass release];
myMyClass = [aClass retain];
}
Now... Where does object1 need to be released?
I'm guessing I need the [object1 release]; line. Correct? And, I will also need to release myMyClass in the dealloc method of the MySuperLayer class. Correct?
What if I change the createClassWithBla method so that it returns an autoreleased instance:
+(id) createClassWithBla:(Bla*)bla
{
return [[[self alloc] initWithBla:bla] autorelease];
}
Then where do I need to release object1? Do I not need to worry about performing -release on any instance of MyClass1, unless I retain it? Is this considered a better practice, to return autoreleased instances from a class method?
Currently if I setup my class methods like this, the application crashes instantly with a "message sent to deallocated instance" error.
What is the best practice regarding passing a single object to other object's methods?
-robodude666