During the development process, you may need to sort by some of the properties of the model.
1. Custom model
@interface*int age ; @end
2. Create Model Object
//Create ModelPerson *liming =[[Person alloc] init]; Liming.name=@"liming"; Liming.age= -; person*zhangjie =[[Person alloc] init]; Zhangjie.name=@"Zhangjie"; Zhangjie.age= -; person*liuxin =[[Person alloc] init]; Liuxin.name=@"liuxin"; Liuxin.age= -; person*wanghua =[[Person alloc] init]; Wanghua.name=@"Wanghua"; Wanghua.age= -;
3. Create a storage array
// creating a storage array Nsmutablearray *personarray = [Nsmutablearray array]; [Personarray addobject:liming]; [Personarray Addobject:zhangjie]; [Personarray addobject:liuxin]; [Personarray Addobject:wanghua];
4. Sort by Model Age attribute
//model sorted by age attributeNsarray *agesortresultarray = [Personarray sortedarrayusingcomparator:^nscomparisonresult (IDObj1,IDobj2) { person*per1 =obj1; person*per2 =Obj2; if(Per1.age >per2.age) {returnnsordereddescending;//Descending}Else if(Per1.age <per2.age) {returnnsorderedascending;//Ascending}Else { returnNsorderedsame;//Equal } }];
5. Printing results
// Print Results for inch Agesortresultarray) { NSLog (@ "per.age =%d", Per.age); }
6.
iOS Custom model sort