具有范围的子阵列

时间:2014-03-21 12:44:25

标签: ios objective-c

我试图将一个对象数组拆分为包含32个对象的较小数组。剩下的就是最后放入阵列。

这是我正在使用的代码

int a = sharedManager.inventoryArray2.count;
float b = a / 33;
int c = ceilf(b);

NSMutableArray *arrayOfArrays = [NSMutableArray array];
int from = 0;
int to = 31;

for (int e = 0; e <= c; e++) {

    if (sharedManager.inventoryArray2.count < to) {

       NSArray *smallArray = [sharedManager.inventoryArray2 subarrayWithRange:NSMakeRange(from, sharedManager.inventoryArray2.count)]; 
        [arrayOfArrays addObject:smallArray];
    }
    else {
       NSArray *smallArray = [sharedManager.inventoryArray2 subarrayWithRange:NSMakeRange(from, to)];
       from = from + (31+1);
       to = from + 31;
       [arrayOfArrays addObject:smallArray];
    } 
}

我收到以下错误。

'NSRangeException', reason: '*** -[NSArray subarrayWithRange:]: range {32, 63} extends beyond bounds [0 .. 83]'   

我不明白,32-63的范围在0-83的范围内。

有什么建议吗?

感谢。 保罗。

3 个答案:

答案 0 :(得分:7)

NSRange指示从该点开始选择的起始点和条目数。所以它实际上意味着&#34;起点32,从&#34;上的那个点选择63个项目,这将超过你的83条目(32 * + * 63)

答案 1 :(得分:2)

NSMakeRange的第二个参数是要创建的长度范围,而不是其中的最后一个索引。因此,您需要相应地更改代码(稍微简化一下):

NSUInteger count = sharedManager.inventoryArray2.count;
NSMutableArray *arrayOfArrays = [NSMutableArray array];
NSUInteger from = 0;
while (from < count) {
    NSRange range = NSMakeRange(from, MIN(32, count-from));
    NSArray *smallArray = [sharedManager.inventoryArray2 subarrayWithRange:range];
    [arrayOfArrays addObject:smallArray];

    from += 32;
}

答案 2 :(得分:1)

否实际上该范围并非如此 NSRange {32,63} =&gt;意味着从索引32取63个元素

以下是文档:

NSRange

A structure used to describe a portion of a series—such as characters in a string or objects in an NSArray object.

typedef struct _NSRange {
  NSUInteger location;
  NSUInteger length;
 } NSRange;

 location
The start index (0 is the first, as in C arrays). For type compatibility with the rest of the system, LONG_MAX is the maximum value you should use for location.

 length
The number of items in the range (can be 0). For type compatibility with the rest of the system, LONG_MAX is the maximum value you should use for length.