我有一个播放歌曲的简单程序。它位于继承的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];
}
为什么我不必分配和初始化对象..我很丢失.. 请帮忙。
答案 0 :(得分:1)
Apple的许多类都有辅助函数,在类级别声明,在helper函数中为您执行alloc和init。他们返回一个随时可用的对象。您可以判断yu是否看到该方法的doc,并且它表示“返回与给定名称关联的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实例。