Pergunta

I am working on an application which works with items distributed in a circular route. The entry point is random.

So when the whole thing starts I need to shift the set with all the positions to a random index.

Example (with arbitrary data):

0:Hungry -> 1:Eating -> 2:Full -> 3:Vomiting*

If I shift this to the index 2 I get the following new set.

2:Full -> 3:Vomiting -> 0:Hungry -> 1:Eating

So how to achieve this in Objective C?

* Sorry, but I needed another element because three elements didn't seem to get the point across...

Foi útil?

Solução

I managed to solve the problem with a category on NSOrderedSet:

NSOrderedSet *newSet = [initialSet orderedSetByShiftingToIndex:2];

This is my Category on NSOrderedSet:

@implementation NSOrderedSet(Shifting)

-(NSOrderedSet *)orderedSetByShiftingToIndex:(int)newIndex{

    if(newIndex == 0 || newIndex > self.count -1){
        return self;
    }

    NSMutableOrderedSet *result = [self mutableCopy];
    NSIndexSet *moveToEnd = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, newIndex -1)];

    int endIndex = result.count-1;

    [result moveObjectsAtIndexes:moveToEnd toIndex:endIndex];

    return result;
}

@end
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top