首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSSound正在工作,但未初始化或分配..

NSSound正在工作,但未初始化或分配..
EN

Stack Overflow用户
提问于 2011-11-14 10:56:27
回答 1查看 333关注 0票数 1

我有一个播放歌曲的简单程序。它位于继承的awakeFromNib方法中。所以..。

代码语言:javascript
复制
-(void)awakeFromNib {
NSSound *song = [NSSound soundNamed:@"MyTune.mp3"];
[song play];
}

我的问题是,为什么这是可行的。为什么我不需要这么做呢

代码语言:javascript
复制
NSSound *song = [[NSSound alloc]init];
song = [NSSound soundNamed:@"MyTune.mp3"];
[song play];
}

它似乎也适用于字符串..我设置了一个NSTextView变量,可以执行以下操作

代码语言:javascript
复制
-(void)awakeFromNib {
NSString *str = [NSString stringWithFormat:@"Hello there!"];
[myTextVariable insertText:str];
}

为什么我不需要分配和初始化对象..我太迷茫了。请帮帮忙。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-14 11:19:17

Apple的许多类都有helper函数,这些函数是在类级别声明的,在helper函数中为您执行alloc和init。它们返回一个可供使用的对象。您可以判断yu是否看到该方法的文档,并且显示类似于“返回与给定名称相关联的NSSound实例”之类的内容。

因此,您的第一个示例是很好的代码:

代码语言:javascript
复制
-(void)awakeFromNib {
NSSound *song = [NSSound soundNamed:@"MyTune.mp3"];
[song play];
}

第二个示例会泄漏内存,因为您先分配指针,然后用[NSSound soundNamed:@"MyTune.mp3"]返回的新对象覆盖指针

代码语言:javascript
复制
  -(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中,您可以看到此方法在内部执行allocinit,并将实例返回给您:

soundNamed

返回与给定名称关联的NSSound实例。

+ (id)soundNamed:(NSString *)soundName

参数

标识声音数据的soundName名称。

返回值

使用soundName标识的声音数据初始化的NSSound实例。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8116806

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档