我正在尝试将数组划分为四个元素的单个数组,其中最后一个数组将包含提醒。例如,如果主数组的长度属性为10,则将创建三个子数组 - 两个包含四个元素,以及两个元素之一。
我现在的代码如下所示:
NSMutableArray *mainMutableArray = [NSMutableArray arrayWithObjects:@"First", @"Second", @"Third", @"Fourth", @"Fifth", @"Sixth", @"Seventh", @"Eighth", nil];
NSMutableArray *mutableArrayOfSubarrays = [NSMutableArray array];
int length = mainMutableArray.count / 4;
int location = 0;
for (int i = 0; i < length; i++)
{
[mutableArrayOfSubarrays addObject:[mainMutableArray subarrayWithRange:NSMakeRange(location, 4)]];
location += 4;
}
这当然仅在提醒等于0时有效。
非常感谢任何帮助。
答案 0 :(得分:2)
好的,我们走了:
int length = mainMutableArray.count;
for (int location = 0; location < length; location+=4)
{
unsigned int Size=length-location;
if (Size>4) Size=4;
[mutableArrayOfSubarrays addObject:[mainMutableArray subarrayWithRange:NSMakeRange(location, Size)]];
}
答案 1 :(得分:1)
如果你使用while
循环,你可以让条件描述你实际上想要做的事情:
NSUInteger length = [mainMutableArray count];
NSUInteger location = 0;
// Until the location is less than four away from the end
while( location <= (length - 4) ){
[mutableArrayOfSubarrays addObject:[mainMutableArray subarrayWithRange:NSMakeRange(location, 4)]];
location += 4;
}
// Pick up the remainder, if any
if( location != length ){
[mutableArrayOfSubarrays addObject:[mainMutableArray subarrayWithRange:NSMakeRange(location, length-location)]];
}
答案 2 :(得分:0)
从length*4
循环到mainMutableArray.count
以获取数组的其余部分。