serge2487
serge2487

Reputation: 441

how to reorder my array?

I have a array that contains all the months in a year like so:

[January,February,March,April,May,June,July,August,September,October,November,December];

When the user types a months in a textfield say like they type "May", I take whats in the textfield and store it as a string. Now I want to reorder my array with May being the first index so my array would now look like this now:

[May, June, July, August, September, October, November, December];

I don't care about the months January - March. I'm having trouble reordering my array correctly? Any ideas on how to do this?

Upvotes: 0

Views: 704

Answers (1)

Regexident
Regexident

Reputation: 29562

This should do:

NSString *monthString = @"May";
NSUInteger monthIndex = [monthsArray indexOfObject:monthString];
NSArray *trimmedMonthsArray = nil;
if (monthIndex != NSNotFound) {
    trimmedMonthsArray = [monthsArray subarrayWithRange:NSMakeRange(monthIndex, [monthArray count] - monthIndex)];
}

As you see it's not so much about reordering (actually it's not about reordering at all) but about cutting out a subarray.

If instead of getting a new trimmed array you want to modify the original mutable array, do this:

NSString *monthString = @"May";
NSUInteger monthIndex = [monthsArray indexOfObject:monthString];
if (monthIndex != NSNotFound) {
    [monthsArray removeObjectsInRange:NSMakeRange(0, monthIndex)];
}

Upvotes: 1

Related Questions