开发者

How to order an array of objects by a certain property in Cocoa Touch?

Let's say I have an array of custom objects. The custom class looks like this

Person
-------
name
number

Now let's say I want to rearrange the array of these objects so that the objects are sorted by the number. How can this be done?开发者_如何学C


1) you have to implement following methods in your Person class

- (NSNumber *)numberForSorting {
  return self.number;
}

- (NSComparisonResult)compare:(Person *)person {
    return [[self numberForSorting] compare:[person numberForSorting]];
}


2) When a Person array is need to be sort you just call

a) in case of NSMutableArray

[peopleMutableArray sortUsingSelector:@selector(compare:)];

b) in case of NSArray

NSArray *sortedPeople = [peopleArray sortedArrayUsingSelector@selector(compare:)];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜