Question

In a certain view I have a bunch of AVAudioPlayer properties, each one is supposed to be played upon a certain user action. While the selected AVAudioPlayer is played, if another AVAudioPlayer was played - it should stop.

To manage that, I've created an Array that holds all the AVAudioPlayer properties and upon user selection, before playing the selected AVAudioPlayer, I wish to go over all the AVAudioPlayers and stop them.

The problem is that the reasonable place to create the Array is at the beginning (let's say, in ViewDidLoad) and at this point none of the AVAudioPlayer properties went through alloc+init - so if I look at the Array in the debugger it shows as empty (number of objects = 0). Currently, I do the alloc+init action only when the user is actually selecting a certain AVAudioPlayer.

I can do alloc+init for all the AVAudioPlayers at the beginning as well, but that will take resources that are not necessarily required.

Is there a way to create this Array without taking the required resources? i.e. create the array with "empty" objects and later have them be allocated and initiated?

Was it helpful?

Solution

I have a similar situation. What I've been doing is:

NSArray *myArray = [NSArray arrayWithObjects:@"",@"",@"",@""];

in viewDidLoad (if my array is going to have 4 objects). Then as I have the information available, I do:

[myArray replaceObjectAtIndex:myLocationToAddValue withObject:myObject];

I got the idea for this looking at some code in a very old project written in a completely different language by someone else from my company. It seems to be working for what I need, and it does have the added benefit that I can loop through my array and check

if ([[myArray objectAtIndex:i] length] == 0) 

to see where I have items already. I should note that the objects I'm adding are going to all be NSStrings - if this loops through and finds an object has been put into the array that isn't a string (or, more generally, doesn't have a "length" method), I'm guessing some nasty stuff would happen, but I haven't checked for that yet.

I'm certain there must be a much better solution, but I'll put it out there since there haven't been any answers to this yet. I figure a sloppy answer that seems to be working is better than no answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top