0

I am deeply sorry as if this is a stupid question. if it is please leave a comment and I will remove it but here is my code below:

NumberedArray = [NSMutableArray arrayWithCapacity:50];
NSUInteger randomNumber = arc4random() % [NumberedArray count];
for (int i = 0; i<randomNumber; i++) {
 // Run some code
}

}

Now I get an error of: Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0X0)

So my best Guess is that the machine is getting confused because I am telling it that this array has capacity of 50 and now pick one of its slots randomly and perform some code is long as the loop is less than this randomly picked number.

but what I really want to do is to have the computer run a code based on randomly picked time interval.

This is a game where this code performs a enemy moving from left to right based on randomly picked time interval. Is this even a right approach? and if not what should I try instead? Thanks.

Andrey Chernukha
21.9k18 gold badges101 silver badges168 bronze badges
asked Mar 10, 2014 at 7:35

1 Answer 1

2

Capacity 50 doesn't mean your array contains 50 elements. Its count is 0. So you perform division by zero and that's why it crashes. Forget about using arrayWithCapacity: or initWithCapacity: because it doesn't mean anything practically helpful.

UPDATE:

If you need random number in a range of 50 then why not use just:

NSUInteger randomNumber = arc4random() % 50;

and initialise your array like this:

numberedArray = [NSMutableArray array];
answered Mar 10, 2014 at 7:40

8 Comments

SO How can I say this array has 50 numbers then?
You can't because it doesn't have 50 numbers
so do you suggest any other approach? Thanks.
sure can you please I mean please wait here for just a moment and let me try this and make sure it works. Actually I think your right. I don't need the capacity thing.
but wait a minute inside the loop, how would these two be connected I mean the random number and array. I think I should just forget about the array right?
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.