我有一个播放歌曲的简单程序。它位于继承的awakeFromNib方法中。所以..。
-(void)awakeFromNib {
NSSound *song = [NSSound soundNamed:@"MyTune.mp3"];
[song play];
}我的问题是,为什么这是可行的。为什么我不需要这么做呢
NSSound *song = [[NSSound alloc]init];
song = [NSSound soundNamed:@"MyTune.mp3"];
[song play];
}它似乎也适用于字符串..我设置了一个NSTextView变量,可以执行以下操作
-(void)awakeFromNib {
NSString *str = [NSString stringWithFormat:@"Hello there!"];
[myTextVariable insertText:str];
}为什么我不需要分配和初始化对象..我太迷茫了。请帮帮忙。
发布于 2011-11-14 11:19:17
Apple的许多类都有helper函数,这些函数是在类级别声明的,在helper函数中为您执行alloc和init。它们返回一个可供使用的对象。您可以判断yu是否看到该方法的文档,并且显示类似于“返回与给定名称相关联的NSSound实例”之类的内容。
因此,您的第一个示例是很好的代码:
-(void)awakeFromNib {
NSSound *song = [NSSound soundNamed:@"MyTune.mp3"];
[song play];
}第二个示例会泄漏内存,因为您先分配指针,然后用[NSSound soundNamed:@"MyTune.mp3"]返回的新对象覆盖指针
-(void)awakeFromNib {
// Create an NSSound object in memory and store the address in song.
NSSound *song = [[NSSound alloc]init];
// If you don't want a memory leak this is your last chance to [song release]
// Create a NSSound object using a helper function and place its address
// in song, over writing the previous address.
song = [NSSound soundNamed:@"MyTune.mp3"];
// We now lost track of the first NSSound object and can't release it because
// we overwrote the address.
[song play];
}从the documentation中,您可以看到此方法在内部执行alloc和init,并将实例返回给您:
soundNamed
返回与给定名称关联的NSSound实例。
+ (id)soundNamed:(NSString *)soundName
参数
标识声音数据的soundName名称。
返回值
使用soundName标识的声音数据初始化的NSSound实例。
https://stackoverflow.com/questions/8116806
复制相似问题