Person 排序 方法重写

main.m

//
//  Person.m
//  sort
//
//  Created by syrcfwzx on 16/1/7.
//  Copyright (c) 2016年 syrcfwzx. All rights reserved.
//

#import "Person.h"

@implementation Person
-(instancetype)initWithClasses:(NSString*)c andName:(NSString*)n andAge:(int)a
{
    self=[super init];
    if(self)
    {
       self.classes=c;
       self.name=n;
       self.age=a;
    }
    return self;
    
}
-(NSString*)description
{
    return [NSString stringWithFormat:@"class=%@ name=%@ age=%d",self.classes,self.name,self.age];
}

-(NSComparisonResult)compareWithClassesAndName:(Person*)p
{
    NSComparisonResult result =[self.classes compare:p.classes];
    if(result ==NSOrderedSame)
    {
        return [self.name compare:p.name];
    }
    else
    {
    return result;
    }
}
-(NSComparisonResult)compareWithAge:(Person*)p
{
    if(self.age ==p.age)
    {
        return NSOrderedSame;
    }
    else if (self.age >p.age)
    {
        return NSOrderedDescending;
    }
    else
    {
        return NSOrderedAscending;
    }
}



@end

.h

//
//  Person.h
//  sort
//
//  Created by syrcfwzx on 16/1/7.
//  Copyright (c) 2016年 syrcfwzx. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject
@property NSString* classes;
@property NSString* name;
@property int age;

-(instancetype)initWithClasses:(NSString*)c andName:(NSString*)n andAge:(int)a;
-(NSComparisonResult)compareWithClassesAndName:(Person*)p;
-(NSComparisonResult)compareWithAge:(Person*)p;


@end

.m

//
//  Person.m
//  sort
//
//  Created by syrcfwzx on 16/1/7.
//  Copyright (c) 2016年 syrcfwzx. All rights reserved.
//

#import "Person.h"

@implementation Person
-(instancetype)initWithClasses:(NSString*)c andName:(NSString*)n andAge:(int)a
{
    self=[super init];
    if(self)
    {
       self.classes=c;
       self.name=n;
       self.age=a;
    }
    return self;
    
}
-(NSString*)description
{
    return [NSString stringWithFormat:@"class=%@ name=%@ age=%d",self.classes,self.name,self.age];
}

-(NSComparisonResult)compareWithClassesAndName:(Person*)p
{
    NSComparisonResult result =[self.classes compare:p.classes];
    if(result ==NSOrderedSame)
    {
        return [self.name compare:p.name];
    }
    else
    {
    return result;
    }
}
-(NSComparisonResult)compareWithAge:(Person*)p
{
    if(self.age ==p.age)
    {
        return NSOrderedSame;
    }
    else if (self.age >p.age)
    {
        return NSOrderedDescending;
    }
    else
    {
        return NSOrderedAscending;
    }
}



@end

 

posted @ 2016-01-09 09:45  33sve  阅读(141)  评论(0编辑  收藏  举报