0

我想显示在文本字段中键入的数字的每个因子以实现这一点,我尝试使用数组。但我总是收到错误'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'。有什么建议可以消除这个错误吗?

       NSMutableArray *array;
        array = [NSMutableArray arrayWithCapacity:100];

        for (factorsNumber=1; factorsNumber<=number; factorsNumber++) {
            if (number%factorsNumber == 0) {
                [array addObject:[NSString stringWithFormat:@"%d", factorsNumber]];
            }

        }

        for (int i = 0; i <= [array count]; i++) {
            factors.text = [NSString stringWithFormat:@"%d", i, [[array objectAtIndex:i] intValue]];
        }
4

3 回答 3

1
for (int i = 0; i <= [array count]; i++) {

应该

for (int i = 0; i <= [array count] - 1; i++) {

或者

for (int i = 0; i < [array count]; i++) {

n-element 数组的有效索引是 0 到n-1

于 2012-07-25T11:50:06.477 回答
1

在您的 for 循环中,删除 = 使其显示为:

for (int i = 0; i < [array count]; i++) 
于 2012-07-25T11:50:35.563 回答
1

你的问题在这里:

for (int i = 0; i < [array count]; i++) { // < instead of <=
    factors.text = [NSString stringWithFormat:@"%d", i, [[array objectAtIndex:i] intValue]];
}
于 2012-07-25T11:54:00.407 回答