gpt4 book ai didi

ios - AVAudioPlayer 属于 ARC 类别

转载 作者:行者123 更新时间:2023-11-29 11:01:56 27 4
gpt4 key购买 nike

我正在尝试为我的应用程序中的所有按钮添加自定义点击声音。我已经为 UIButton 创建了一个类类别,其中包含以下代码:

NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle bundleWithIdentifier:@"com.apple.UIKit"] pathForResource:@"Tock" ofType:@"aiff"]];
NSError *error;

AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];

if(audioPlayer == nil){
NSLog(@"%@", [error description]);
} else{
[audioPlayer play];
}

所有这一切都在执行:- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

但据我了解,ARC(我正在使用)存在一个常见问题。 audioPlayer 对象似乎在播放声音之前被释放。我还查看了 AudioServicesPlaySystemSound();。但目前这对我来说别无选择,因为我的应用程序中需要一个音量 Controller ,而且我发现没有办法在不离开应用程序的情况下更改系统音量。

我的问题是:有没有办法在 UIButton 类类别中对我的 audioPlayer 对象进行强引用?或者是否有任何其他可能更好的方法来实现此目的?

最佳答案

在类别中添加任何对象关系时,始终值得查看关联对象。使用 objc_setAssociatedObject()objc_getAssociatedObject() 函数。确保为键使用唯一的指针值,在您的情况下,您肯定希望使用其中一种保留关联策略来确保您的对象的生命周期是合适的。

关于ios - AVAudioPlayer 属于 ARC 类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15472994/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com