具有范围的子arrays

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

这是我正在使用的代码

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的范围内。

任何建议?

谢谢。 保罗。

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

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; } 

实际上,范围不起作用,这样NSRange {32,63} =>意味着从索引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.