Main
1 #import<Foundation/Foundation.h>2 #import "Person.h"3 4 intMainintargcConst Char*argv[]) {5 @autoreleasepool {6Person *stu1=[[person alloc]initclasses:@"iOS8"Andname:@"Zxy"Andage: +];7Person *stu2=[[person alloc]initclasses:@"iOS6"Andname:@"Hyu"Andage: -];8Person *stu3=[[person alloc]initclasses:@"iOS8"Andname:@"AWE"Andage: -];9Person *stu4=[[person alloc]initclasses:@"iOS6"Andname:@"MKI"Andage: at];TenPerson *stu5=[[person alloc]initclasses:@"iOS8"Andname:@"BYU"Andage: -]; OneNsarray *arr=[nsarray Arraywithobjects:stu1,stu2,stu3,stu4,stu5,nil];//put the instantiated object into the array ANsarray *sortarr1=[arr sortedarrayusingselector: @selector (comparewithclassandname:)];//deposit the sorted array into the new array Sortarr - //NSLog (@ "%@", SORTARR1); //with description output - for(Person *personinchsortArr1) { theNSLog (@"Name:%@, Class:%@, Age:%d", person.name,person.classes,person.age); - } -Nsarray *sortarr2=[arr sortedarrayusingselector: @selector (comparewithage:)];//Sort by age - for(Person *personinchsortArr2) { +NSLog (@"Name:%@, Class:%@, Age:%d", person.name,person.classes,person.age); - } + } A return 0; at}
Person.h:
1 #import<Foundation/Foundation.h>2 3 @interfacePerson:nsobject4@property NSString *classes;5@property NSString *name;6@propertyintAge ;7-(Instancetype) initclasses: (NSString *) classes Andname: (NSString *) name Andage: (int) Age;//Initializing Data8-(Nscomparisonresult) Comparewithclassandname: (person *) person;//compare names and Classes9-(Nscomparisonresult) Comparewithage: (person *) person;//Compare AgeTen @end
PERSON.M:
1 #import "Person.h"2 3 @implementation Person4-(Instancetype) initclasses: (NSString *) classes Andname: (NSString *) name Andage: (int) Age;//Initializing Data5 {6Person *person=[[Person alloc]init];7person.classes=classes;//assigns a value to the classes, and the later classes data that is instantiated in the main function is passed in the formal parameter8Person.name=name;9Person.age=Age ;Ten returnPerson ; One } A-(Nscomparisonresult) Comparewithclassandname: (person *) person;//compare names and Classes - { -Nscomparisonresult result=[self.classes compare:person.classes];//Compare the classes in this class and the classes that pass in the if(result==nsorderedsame) { - return[Self.name Compare:person.name];//Return comparison value - } - Else{ + returnresult; - } + } A-(Nscomparisonresult) Comparewithage: (person *) person;//Compare Age at { - if(self.age==person.age) { - returnNsorderedsame; - } - Else if(self.age>person.age) { - returnnsordereddescending; in } - Else{ to returnnsorderedascending; + } - } the-(NSString *) description{//rewrite description to make printed out with formatting * return[NSString stringWithFormat:@"class:%@ name:%@ age:%d", Self.classes,self.name,self.age];//formatted output $ }Panax Notoginseng @end
(The above code is working correctly in Xcode 6.4)
[Example-nsarray sort]-Sort student information by class, name and age