Reputation: 495
I am creating some custom objects to practice with. I have three classes Song, Playlist and Music. It's easy to instantiate a new Song from my main program, but I was thinking that I should create a method in the Music class to create a new Song and return it to the main program. Here is where I become confused. After the object is created, where and when do I release it. Do I create it and retain it in the Music method and then release it in the main program? I think that I would need to create another Song object in the main program to receive the returned Song. I would greatly appreciate some thoughts on this?
Thanks,
gfgruvin
Upvotes: 0
Views: 364
Reputation:
The idiomatic Cocoa design principle is that if you don't create/retain objects using -alloc, -retain, -copy or -mutableCopy, then you're not responsible for releasing them; thus you don't have to (and should not) release them. Memory management in these cases is done like this: the creator class created the object, so it's responsible for releasing it. Since the creator class doesn't know when to release the object, it will simply -autorelease it. In your case, this will be done like this (supposed your Song class has some kind of a Title property):
@implementation Music
+ (Song *) songWithTitle:(NSString *)title
{
Song *s = [[[Song alloc] init] autorelease]; // autorelease make our conscience happy
s.title = title;
return s;
}
@end
Hope this helps.
Upvotes: 1