lunadiviner
lunadiviner

Reputation: 509

array shuffling not working, objective C

I have two arrays of animations, one a "before" animation and one an "after" animation, that need to go together in my animation blocks. I want to randomize the order in which they execute. I created an array of numbers, 0-3, like so:

NSNumber *w = [NSNumber numberWithUnsignedInt: 0];
NSNumber *x = [NSNumber numberWithUnsignedInt: 1];
NSNumber *y = [NSNumber numberWithUnsignedInt: 2];
NSNumber *z = [NSNumber numberWithUnsignedInt: 3];
NSArray *numbers = [[NSArray alloc] initWithObjects: w, x, y, z, nil];

I'm using this category to randomize the array, and then:

 [numbers shuffledArray];

Then I have another set of ints that I use to get the numbers in the theoretically shuffled away, and use these in my animation blocks:

int ww = [[numbers objectAtIndex:0] integerValue];
int xx = [[numbers objectAtIndex:1] integerValue];
int yy = [[numbers objectAtIndex:2] integerValue];
int zz = [[numbers objectAtIndex:3] integerValue];

[UIView animateWithDuration:.85 delay:3 options:opts animations:[animations objectAtIndex:ww] completion:[completions objectAtIndex:ww]];
[UIView animateWithDuration:.85 delay:8 options:opts animations:[animations objectAtIndex:xx] completion:[completions objectAtIndex:xx]];

etc. The reason I don't just do use "animations:[animations objectAtIndex:[numbers objectAtIndex:0]] is because the compiler was throwing an "Incompatible pointer to integer conversion sending type 'id' to parameter of type 'NSUInteger' (aka 'unsigned int')" when I did it that way, which I tried to fix by typing the original ints as unsigned ints but no luck there.

The code gives me no errors and everything runs just fine, except that nothing is randomized; but it's in the order in which I placed everything in the first place. Any ideas as to where I'm going wrong? I've tried a bunch of other randomization functions and nothing seems to work.

Upvotes: 0

Views: 206

Answers (2)

MarkPowell
MarkPowell

Reputation: 16540

From the code you posted, it appears you are not storing the returned NSArray anywhere. That is, shuffledArray does not shuffle the array in place, it returns a new shuffled array. Make sure you are storing it:

numbers = [numbers shuffledArray];

EDIT: If you store the returned array in numbers make sure you release it or set it to autorelease before, unless you are using ARC.

Upvotes: 2

matt
matt

Reputation: 535118

shuffledArray doesn't shuffle the array: it returns a shuffled array. You are not capturing that returned result. So:

NSArray* result = [numbers shuffledArray];

Now result will be shuffled.

Upvotes: 2

Related Questions