是否有一種簡單的方法可以將序列中的數字轉換爲數組?Objective-C - 將數組數組轉換爲數組,並按順序編號
NSArray *numbers = @[@1,@2,@5,@3];
// Transformed arrays
//NSArray *numbersInSequence = @[@1,@2,@3];
//NSArray *numbersInSequence2 = @[@5];
編輯:
我修改了代碼中Richard's answer來得到它的工作。
NSArray *arraysBySplittingNumbersInOrder(NSArray *input) {
// sort 'input'
input = [input sortedArrayUsingSelector:@selector(compare:)];
NSMutableArray *results = [NSMutableArray array];
if (input.count) {
int start = 0;
int last = INT_MIN;
for (int i = 0; i < input.count; i++) {
BOOL lastItem = i == input.count - 1;
// The first item of the array
if (i == 0) {
if (lastItem) {
[results addObject:input];
break;
}
last = [input[i] intValue];
continue;
}
int cur = [input[i] intValue];
if (cur != last + 1) {
// pull out the next array
[results addObject:[input subarrayWithRange:NSMakeRange(start, i - start)]];
start = i;
}
// The last item of the array
if (lastItem) {
[results addObject:[input subarrayWithRange:NSMakeRange(start, i - start + 1)]];
}
last = cur;
}
}
return results;
}
你可以在這裏找到答案:http://stackoverflow.com/questions/805547/how-to-sort- an-nsmutablearray -with-custom-objects-in-it – Dave
@Dave不,這不是必要的。他只需要使用內置的'-compare:'選擇器對其進行排序,然後遍歷數組一次。 –