[英]iPhone: How to create dynamic instances for any built-in class object?
I want to create dynamic instances for a built in class object. 我想为内置类对象创建动态实例。 I am not sure how to achieve this.
我不知道如何实现这一目标。 For example, the below audio player object instance i want to create dynamically, so that I can play dynamic multiple data.
例如,我想动态创建下面的音频播放器对象实例,以便我可以播放动态多个数据。
audioPlayer = [[AVAudioPlayer alloc] initWithData:pData error:nil];
instead of this, i want to be something like below, 而不是这个,我想成为下面的东西,
audioPlayer1 = [[AVAudioPlayer alloc] initWithData:pData error:nil];
audioPlayer2 = [[AVAudioPlayer alloc] initWithData:pData error:nil];
audioPlayer3 = [[AVAudioPlayer alloc] initWithData:pData error:nil];
Here, 1, 2, 3 can be added dynamically, because i don't know how many i have to add at once, it has to be dynamically created. 这里,可以动态添加1,2,3,因为我不知道有多少我必须一次添加,它必须动态创建。
I though i can do like, 我虽然能做到,
AVAudioPlayer *[NSString stringWithFormat:@"audioPlayer%d", value] = [[AVAudioPlayer alloc] initWithData:pData error:nil];
But this is not acceptable. 但这是不可接受的。
Could someone help me on this to resolve? 有人可以帮我解决这个问题吗?
Just use a loop to create the instances and put them into a mutable array. 只需使用循环来创建实例并将它们放入可变数组中。
NSMutableArray *players = [NSMutableArray array];
for (int i = 0; i < 3; i++) {
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:pData error:nil];
[players addObject:audioPlayer];
}
As @Ole Begemann
suggested, put the dynamic creations in a for loop. 正如
@Ole Begemann
建议的那样,将动态创作置于for循环中。 But, What I would do is create a method accepting a dynamic
value of how many need to be created: 但是,我要做的是创建一个接受需要创建的
dynamic
值的方法:
-(void)createAudioPlayers:(int)count {
//Assuming `players` array is declared in your header as an NSMutableArray and initialized.
pData = ... // your data
for (int i = 0; i < count; i++) {
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:pData error:nil];
[audioPlayer play];
[players addObject:audioPlayer];
}
}
Now you can simply pass an int
value, on how many players you want to create. 现在您可以简单地传递一个
int
值,表示您想要创建的玩家数量。
[self createAudioPlayers:4];
or 要么
[self createAudioPlayers:8];
Hope this helps ! 希望这可以帮助 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.