0

I have an NSArray, with objects ordered like so:

  • a
  • b
  • c
  • d
  • e
  • f

I would like to enumerate through this array in this order:

  • c
  • d
  • e
  • f
  • a
  • b

i.e. starting at some point that is not the beginning, but hitting all the items.

I imagine this is a matter of sorting first and then enumerating the array, but I'm not sure if that's the best technique... or, frankly, how to sort the array like this.

Edit

Adding details: These will be relatively small arrays, varying from 3 to 10 objects. No concurrent access. I'd like to permanently alter the sort order of the array each time I do this operation.

Kenny Winker
  • 11,919
  • 7
  • 56
  • 78
  • not that it matters, but I'm curious. Why do it this way? – Alex Feb 02 '11 at 23:07
  • Please describe the entire lifecycle of the datastructure (preferably what you're storing in it, how many items you expect to have, how often/fast you need to access it, whether you need the enumeration to be resilient to concurrent modification, etc.) – Nicholas Riley Feb 02 '11 at 23:11
  • Re: Alex. Hard to describe. I have two discs of points, one inside the other. When you rotate the inner disk of points the objects in the inner array need to associate with the corresponding objects in the outer array (where the points are fixed). I'm sure I could hack something together using for loops and offsets and stuff, but I'd like to get better at sorting arrays. – Kenny Winker Feb 02 '11 at 23:14

1 Answers1

1
NSUInteger n = arr.count;
for (NSUInteger i = 0; i < n; ++i) {
    id e = [arr objectAtIndex:(start + i)%n];
    // ...
}
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • 1
    You should use `NSUInteger`, not `int`, for indexes into and the count of an NSArray. – Peter Hosey Feb 02 '11 at 23:52
  • Because the type declared by NSArray for these things is `NSUInteger`. Concrete differences include difference in signedness (`NSUInteger` is unsigned; `int` is signed) and, on some architectures, difference in size (`NSUInteger` is 64 bits on 64-bit architectures), but even if there were no differences, it is still better to use the correct type than some other type that happens to work out the same. – Peter Hosey Feb 03 '11 at 17:26