开发者

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

开发者 https://www.devze.com 2023-01-17 08:26 出处:网络
Let\'s say I have an array of custom objects. The custom class looks like this Person ------- name number

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

精彩评论

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