0

我试图将一个数组分成四个元素的单独数组,其中最后一个数组将包含提醒。例如,如果主数组的长度属性为 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 时才有效。

任何帮助将不胜感激。

4

3 回答 3

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)]];
}
于 2012-07-15T17:07:41.693 回答
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)]];
}
于 2012-07-15T17:21:41.790 回答
0

length*4从to循环mainMutableArray.count以获取数组的其余部分。

于 2012-07-15T17:09:00.193 回答