我需要创建一个名为primaryKey
的新NSNumber或整数属性,以包含在我创建的所有AVAudioPlayer个对象中,以便我可以在audioPlayerDidFinishPlaying
中读取该属性的值回调并确切地知道播放了哪个数据库记录。
我需要这样做的原因是:我无法使用播放器URL property来确定它是哪个数据库记录,因为在播放列表中可以多次使用相同的声音文件。
如何将新属性添加到现有的iOS类中?
示例:
AVAudioPlayer *newAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
self.theAudio = newAudio; // automatically retain audio and dealloc old file if new file is loaded
if (theAudio != nil) [audioPlayers addObject:theAudio];
[newAudio release];
[theAudio setDelegate: theDelegate];
[theAudio setNumberOfLoops: 0];
[theAudio setVolume: callVolume];
// This is the new property that I want to add
[theAudio setPrimaryKey: thePrimaryKey];
[theAudio play];
然后我会在回调中检索它,如下所示:
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
NSNumber *finishedSound = [NSNumber numberWithInt:[player primaryKey]];
// Do something with this information now...
}
答案 0 :(得分:3)
您可以创建子类并添加属性,就像子类化任何内容一样。
@interface MyAudioPlayer : AVAudioPlayer
@property (nonatomic) int primaryKey;
@end
@implementation MyAudioPlayer
@synthesize primaryKey = _primaryKey;
@end
MyAudioPlayer *player = [[MyAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.primaryKey = thePrimaryKey;
...
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
if ([player isKindOfClass:[MyAudioPlayer class]]) {
MyAudioPlayer *myPlayer = (MyAudioPlayer *)player;
NSNumber *primaryKeyObject = [NSNumber numberWithInt:myPlayer.primaryKey];
...
}
}
答案 1 :(得分:1)
一种简单的方法可能是创建一个NSMutableDictionary并使用您创建的AVAudioPlayers作为KEYS,主键(或整个字典)作为相应的VALUE。然后,当玩家停止播放(或错误)时,您可以在字典中查找并恢复任何您喜欢的内容。