-2

Have a problem here.

I have a NSMutableArray, where I have the following numbers:

99,
161,
178,
179,
180,
181,
182,
184,
185,
194,
195,
196,
205,
206,
210,
218,
337,  <------- Here is the 337
227,
232,
240,
244,
346,
352,
353

As you can se there is a 337 between the 218 and 227. How can I make the 337 to go forward while the next number is smaller than 337?

Or in other words, how do I make my NSMutableArray Ascendent?

Charls Pico
  • 61
  • 2
  • 9

3 Answers3

0

It is not very clear what you have tried already and what you might have done wrong, when there is no code to evaluate. Please, check the NSArray class reference to try out the versions of sorting methods that apply best to your problem. Also remember that the array should hold objects, in your case NSNumbers. Then you can use the following method:

sortedArrayUsingFunction:context: Returns a new array that lists the receiving array’s elements in ascending order as defined by the comparison function comparator.

Declaration SWIFT func sortedArrayUsingFunction(_ comparator: CFunctionPointer<((AnyObject!, AnyObject!, UnsafeMutablePointer) -> Int)>, context context: UnsafeMutablePointer) -> [AnyObject] OBJECTIVE-C - (NSArray )sortedArrayUsingFunction:(NSInteger ()(id, id, void *))comparator context:(void *)context Discussion The new array contains references to the receiving array’s elements, not copies of them.

The comparison function is used to compare two elements at a time and should return NSOrderedAscending if the first element is smaller than the second, NSOrderedDescending if the first element is larger than the second, and NSOrderedSame if the elements are equal. Each time the comparison function is called, it’s passed context as its third argument. This allows the comparison to be based on some outside parameter, such as whether character sorting is case-sensitive or case-insensitive.

Given anArray (an array of NSNumber objects) and a comparison function of this type:

NSInteger intSort(id num1, id num2, void *context) { int v1 = [num1 intValue]; int v2 = [num2 intValue]; if (v1 < v2) return NSOrderedAscending; else if (v1 > v2) return NSOrderedDescending; else return NSOrderedSame; } A sorted version of anArray is created in this way:

NSArray *sortedArray; sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL]; Import Statement import Foundation

Availability Available in iOS 2.0 and later.

MacUserT
  • 1,760
  • 2
  • 18
  • 30
0

You can try with:

NSArray *arrayOfNumbers = @[@(4), @(2), @(13), @(156), @(1), @(-2)];
NSSortDescriptor *lowestToHighest = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES];
arrayOfNumbers = [arrayOfNumbers sortedArrayUsingDescriptors:@[lowestToHighest]];
diegof29
  • 1
  • 1
0

Do this but make sure your array is of NSNumbers first, not just plain int:

[arrayOfNumbers sortedArrayUsingSelector:@selector(compare:)];
MobileMon
  • 8,341
  • 5
  • 56
  • 75