开发者

Sort NSArray based on struct property

I have an NSArray of 开发者_如何学Goobjects.

Each object has a property struct LOCATION that stores int x and int y.

LOCATION represents the location of the object on a 10x10 board.

I would like to sort the NSArray of objects starting with the top left (0,0) location down to the bottom right (9, 9) location, sorting each object in the each row first

What is the easiest way to do this?


You have a few options, all of them listed under "Sorting" in the NSArray Class Reference. I recommend you add a compare method to the class stored in the array (call itcompareTo: or something similar) and use sortedArrayUsingSelector:. The code would look something like the following:

// In MyObject.m
- (NSComparisonResult)compareTo:(MyObject *)other {
  if (self.location.y < other.location.y && self.location.x < other.location.x) {
    return NSOrderedAscending;
  } else if (self.location.y == other.location.y && self.location.x == other.location.x) {
    return NSOrderedSame;
  } else {
    return NSOrderedDescending;
  }
}

// In some .m file.
NSArray *sortedArray = [objects sortedArrayUsingSelector:@selector(compareTo:)];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜