Stella
Stella

Reputation: 1868

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.

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?

Upvotes: 1

Views: 159

Answers (2)

skram
skram

Reputation: 5314

As @Ole Begemann suggested, put the dynamic creations in a for loop. But, What I would do is create a method accepting a dynamic value of how many need to be created:

-(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.

[self createAudioPlayers:4];

or

[self createAudioPlayers:8];

Hope this helps !

Upvotes: 0

Ole Begemann
Ole Begemann

Reputation: 135548

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];
}

Upvotes: 4

Related Questions