将 NSArray 拆分为固定大小,其余的
Split an NSArray into a fixed size and the rest
我的项目中有一个 NSArray
,它有将近 12 个元素。我想把这个数组分成 2 个数组。我想要第一个数组中的前 3 个元素和第二个数组中的其余元素 NSArray
.
基于the answer of Alex Reynolds:
你应该制作一个长度为 3 的范围,并用它制作数组的前半部分,然后修改其位置和长度并创建数组的后半部分。
NSArray *firstThreeArray;
NSArray *otherArray;
NSRange threeRange;
threeRange.location = 0;
threeRange.length = 3;
firstThreeArray = [wholeArray subarrayWithRange:threeRange];
threeRange.location = threeRange.length;
threeRange.length = [wholeArray count] - threeRange.length;
otherArray = [wholeArray subarrayWithRange:threeRange];
作为 NSArray
的类别:
@implementation NSArray (NSArray_Slicing)
- (NSArray *)subarraysFromIndex:(int)index {
return @[[self sliceToIndex:index], [self sliceFromIndex:index]];
}
- (NSArray *)sliceFromIndex:(int)index {
NSMutableArray*mutArray = [self mutableCopy];
NSRange range = NSMakeRange(index, self.count - index);
return [mutArray subarrayWithRange:range];
}
- (NSArray *)sliceToIndex:(int)index {
NSMutableArray*mutArray = [self mutableCopy];
NSRange range = NSMakeRange(0, index);
return [mutArray subarrayWithRange:range];
}
@end
然后调用它:
NSArray *array = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12];
NSLog(@"First three: %@", [array sliceToIndex:3]);
NSLog(@"Remaining: %@", [array sliceFromIndex:3]);
NSLog(@"Sliced: %@", [array subarraysFromIndex:3]);
NSLog(@"Original: %@", array);
我的项目中有一个 NSArray
,它有将近 12 个元素。我想把这个数组分成 2 个数组。我想要第一个数组中的前 3 个元素和第二个数组中的其余元素 NSArray
.
基于the answer of Alex Reynolds:
你应该制作一个长度为 3 的范围,并用它制作数组的前半部分,然后修改其位置和长度并创建数组的后半部分。
NSArray *firstThreeArray;
NSArray *otherArray;
NSRange threeRange;
threeRange.location = 0;
threeRange.length = 3;
firstThreeArray = [wholeArray subarrayWithRange:threeRange];
threeRange.location = threeRange.length;
threeRange.length = [wholeArray count] - threeRange.length;
otherArray = [wholeArray subarrayWithRange:threeRange];
作为 NSArray
的类别:
@implementation NSArray (NSArray_Slicing)
- (NSArray *)subarraysFromIndex:(int)index {
return @[[self sliceToIndex:index], [self sliceFromIndex:index]];
}
- (NSArray *)sliceFromIndex:(int)index {
NSMutableArray*mutArray = [self mutableCopy];
NSRange range = NSMakeRange(index, self.count - index);
return [mutArray subarrayWithRange:range];
}
- (NSArray *)sliceToIndex:(int)index {
NSMutableArray*mutArray = [self mutableCopy];
NSRange range = NSMakeRange(0, index);
return [mutArray subarrayWithRange:range];
}
@end
然后调用它:
NSArray *array = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12];
NSLog(@"First three: %@", [array sliceToIndex:3]);
NSLog(@"Remaining: %@", [array sliceFromIndex:3]);
NSLog(@"Sliced: %@", [array subarraysFromIndex:3]);
NSLog(@"Original: %@", array);