0

I would like to rearrange an NSMutableArray in a very particular way. This

1, 7, 0, 45, 0, 0, 500, 0

Would become like this

1, 7, 45, 500, 0, 0, 0, 0.

Anything that's not 0 (or some special value) should be sorted normally at the beginning, with the 0s at the end. How would I do this?

This is going to be used for deletion of a cell from a table view, my table works so that cell index will always point to element in an array. If I leave a blank space the index would no longer lineup with the array.

Curlip
  • 395
  • 1
  • 3
  • 15
  • You can't have `nil` in an array - what is actually in your array? – Paul.s Aug 01 '15 at 09:27
  • 3
    Well that's sorting; just with some sort of weird ass order. There are lots of examples of doing that on this site. – trojanfoe Aug 01 '15 at 09:30
  • This link will help you http://stackoverflow.com/questions/5649850/sorting-array-in-increasing-order – sohil Aug 01 '15 at 09:38
  • Thought I'd say that it's objects not numbers, I'm using it for deletion – Curlip Aug 01 '15 at 09:43
  • 2
    You should show your real problem or you will receive answers solving a different problem... – Wain Aug 01 '15 at 10:16
  • Seems like filtering might make more sense in this case. Futher to Wain's comment, see [What is the X/Y problem?](http://meta.stackexchange.com/q/66377) – jscs Aug 01 '15 at 19:31

2 Answers2

2

You could sort something like

[array sortUsingComparator:^(NSNumber *obj1, NSNumber *obj2) {
  if ([obj1 isEqualToNumber:@0]) {
    return NSOrderedDescending;
  } else if ([obj2 isEqualToNumber:@0]) {
    return NSOrderedAscending;
  }

  return [obj1 compare:obj2];
}];
Paul.s
  • 38,494
  • 5
  • 70
  • 88
  • Sorry I'm new to iOS and Objective-c how would I use this – Curlip Aug 01 '15 at 09:39
  • Show the code you have and then I can show how it fits in – Paul.s Aug 01 '15 at 09:44
  • I haven't attempted yet, I'm more looking for the therory. (they are objects not numbers) – Curlip Aug 01 '15 at 09:46
  • What does it return. (NSOrderedAcending. Ect) – Curlip Aug 01 '15 at 09:48
  • Check the [docs](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/#//apple_ref/occ/instm/NSMutableArray/sortUsingComparator:) the blocks return will be of type `NSComparisonResult` -> `NSOrderedAscending`, `NSOrderedDescending` or `NSOrderedSame` – Paul.s Aug 01 '15 at 09:57
0

Don't worry simply using removeObjectAtIndex: worked well for what I wanted. removeObjectAtIndex: shifts all objects by offsetting their index by -1. If anyone needs to keep the 0's at the end then you could just add them after deleting them.

Curlip
  • 395
  • 1
  • 3
  • 15