【问题标题】:NSSound working, but not initialized or allocated..NSSound 工作,但未初始化或分配..
【发布时间】:2011-12-28 08:15:18
【问题描述】:

我有一个播放歌曲的简单程序。它在继承的 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];
}

为什么我不必分配和初始化对象..我很迷茫.. 请帮忙。

【问题讨论】:

  • 有人吗?我只是很难理解这一点。

标签: objective-c memory object methods memory-management


【解决方案1】:

Apple 的许多类都有辅助函数,在类级别声明,在辅助函数内部为您执行 alloc 和 init。他们返回一个准备使用的对象。您可以判断您是否看到该方法的文档,并且它说类似“返回与给定名称关联的 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 你可以看到这个方法在里面做allocinit 并将实例返回给你:

soundNamed

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

+ (id)soundNamed:(NSString *)soundName

参数

声音名称 标识声音数据的名称。

返回值

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

【讨论】:

  • 好的,所以在我的第二个示例中,我包括 [歌曲发布];会是一样的吗?
  • 你没有释放它,因为你没有分配它。当您使用辅助函数时,Apple 的代码将为您控制释放。它这样做是因为 分配了它。
  • 我想我没明白你的意思。如果您询问在第二个示例中的第 2 行和第 3 行之间插入一个版本,那么是的。它在功能上与第一个示例相同,但浪费了 CPU 周期和编码。
  • 谢谢理查德,是的,这就是我要问的。基本上,如果我插入[歌曲发布]; [歌曲播放]之后;然后它会处理泄漏......
  • 另外,我不知道辅助函数。有没有一种简单的方法来判断哪些类有它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-29
  • 1970-01-01
  • 2021-05-24
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多