YIem`s Blog -心比天高命比纸薄-链接找不到的请在站内搜索内容!

OC-排序-自定义类型对象的排序

.main.m 代码

 /**********    自定义类型对象的排序  *****************/

Person *per1 = [[Person alloc] initWithName:@"Long" age:22];
Person *per2 = [[Person alloc] initWithName:@"Bian" age:18];
Person *per3 = [[Person alloc] initWithName:@"YI" age:20];
NSMutableArray *perArr = [NSMutableArray arrayWithObjects:per1, per2, per3, nil];

[perArr sortUsingSelector:@selector(compareWithName:)];
//[perArr sortedArrayUsingSelector:@selector(compareWithAge:)];

for (Person *per in perArr) {
    NSLog(@"%@ %ld", per.name, per.age);
}

Person.h 代码

@property (nonatomic, copy) NSString *name;

@property (nonatomic, assign) NSInteger age;

Person.m 代码

- (instancetype)initWithName:(NSString *)name
                     age:(NSInteger)age

{

self = [super init];
if (self) {
    self.name = name;
    self.age = age;
}
return self;

}

{
return [self.name compare:per.name] ;
}

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »