简体   繁体   English

NSMutableArray arrayWithCapacity问题

[英]NSMutableArray arrayWithCapacity issue

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) 现在我得到一个错误:线程1:EXC_ARITHMETIC(代码= EXC_I386_DIV,子代码= 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. 所以我最好的猜测是机器变得混乱,因为我告诉它这个数组的容量为50,现在随机选择其中一个插槽并执行一些代码,因为循环小于这个随机选择的数字。

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. 谢谢。

Capacity 50 doesn't mean your array contains 50 elements. 容量50并不意味着您的数组包含50个元素。 Its count is 0. So you perform division by zero and that's why it crashes. 它的计数为0.所以你执行除零,这就是它崩溃的原因。 Forget about using arrayWithCapacity: or initWithCapacity: because it doesn't mean anything practically helpful. 忘记使用arrayWithCapacity:initWithCapacity:因为它并不意味着任何实际上有用的东西。

UPDATE: 更新:

If you need random number in a range of 50 then why not use just: 如果您需要50的范围内的随机数,那么为什么不使用:

NSUInteger randomNumber = arc4random() % 50;

and initialise your array like this: 并像这样初始化你的数组:

numberedArray = [NSMutableArray array];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM