I have a simple program that plays a song. It’s in the inherited awakeFromNib method. So..
-(void)awakeFromNib {
NSSound *song = [NSSound soundNamed:@"MyTune.mp3"];
[song play];
}
My question is, why does this work. How come I don’t have to do this
NSSound *song = [[NSSound alloc]init];
song = [NSSound soundNamed:@"MyTune.mp3"];
[song play];
}
It also seems to work with strings too.. I have a NSTextView variable set up and I can do the following
-(void)awakeFromNib {
NSString *str = [NSString stringWithFormat:@"Hello there!"];
[myTextVariable insertText:str];
}
Why didn’t I have to alloc and init the objects.. I am so lost..
Please help.
Many of Apple’s classes have helper functions, declared at the class level which do the alloc and init for you, inside the helper function. They return a ready to use object. You can tell if yu see the doc for the method and it says something like “Returns the NSSound instance associated with a given name.”
Your first example is therefore good code:
Your second example leaks memory because you alloc and then overwrite your pointer with a new object returned by
[NSSound soundNamed:@"MyTune.mp3"]:From the documentation you can see that this method is doing the
allocandinitinside it and returning the instance to you:soundNamed:
Returns the NSSound instance associated with a given name.
+ (id)soundNamed:(NSString *)soundName
Parameters
soundName
Name that identifies sound data.
Return Value
NSSound instance initialized with the sound data identified by soundName.