OC - SortArray

3286 단어 배열배열 정렬
#import <Foundation/Foundation.h>
#import "Person.h"




int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
//  Person  
        Person *per1 = [[Person alloc ] initWithName:@"zhangSan" sex:@"male" age:@"25"];
        Person *per2 = [[Person alloc] initWithName:@"liSi" sex:@"female" age:@"22"];
        Person *per3 = [[Person alloc] initWithName:@"maHuaTeng" sex:@"male" age:@"38"];
        Person *per4 = [[Person alloc] initWithName:@"maYun" sex:@"male" age:@"40"];
        
        // 
        NSMutableArray *array = [NSMutableArray array];
        // 
        [array addObject:per1];
        [array addObject:per2];
        [array addObject:per3];
        [array addObject:per3];
        [array addObject:per4];
//        [@"a"compare:@"b"];
        
        
        
        // ( )
        [array sortUsingSelector:@selector(compareByNameWithOther:)];
        NSLog(@"%@",array);
        
        [array sortUsingSelector:@selector(compareByAgeWithOther:)];
        NSLog(@"%@",array);
        
        
    }
    return 0;
}

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    NSString *_name;
    NSString *_sex;
    NSString *_age;
}
-(id)initWithName:(NSString *)name
              sex:(NSString *)sex
              age:(NSString *)age;

-(void)setName:(NSString *)name;
-(NSString * )name;

-(void)setSex:(NSString *)sex;
-(NSString *)sex;

-(void)setAge:(NSString *)age;
-(NSString *)age;

// 
-(NSString *)description;


// 
-(NSComparisonResult)compareByNameWithOther:(Person *)anotherPerson;

// 
-(NSComparisonResult)compareByAgeWithOther:(Person *)anotherPerson;


@end

#import "Person.h"

@implementation Person
-(id)initWithName:(NSString *)name
              sex:(NSString *)sex
              age:(NSString *)age
{
    if ([super init]) {
        _name = name;
        _sex = sex;
        _age = age;
    }return self;
}

-(void)setName:(NSString *)name
{
    _name = name;
}
-(NSString * )name
{
    return _name;
}

-(void)setSex:(NSString *)sex
{
    _sex = sex;
}
-(NSString *)sex
{
    return _sex;
}

-(void)setAge:(NSString *)age
{
    _age = age;
}
-(NSString *)age
{
    return _age;
}


-(NSString *)description
{
    return [NSString stringWithFormat:@"name:%@,sex:%@,age:%@",_name,_sex,_age];
}


// 
-(NSComparisonResult)compareByNameWithOther:(Person *)anotherPerson
{
    if ([self.name compare:anotherPerson.name] > 0  ) {
        // , 
        return NSOrderedDescending;
    }else if([self.name compare:anotherPerson.name] < 0){
        // , 
        return NSOrderedAscending;
    }
    // , 
    return NSOrderedSame;
    }


// 
-(NSComparisonResult)compareByAgeWithOther:(Person *)anotherPerson
{
    if ([self.age compare:anotherPerson.age] > 0) {
        
        return NSOrderedDescending;
    }else if ([self.age compare:anotherPerson.age] < 0){
        
        return NSOrderedAscending;
    }
    
    return NSOrderedSame;
}

@end

좋은 웹페이지 즐겨찾기