IOS custom model sorting and iosmodel sorting
During the development process, you may need to sort by a certain attribute of the model.
1. Custom model
@interface Person : NSObject@property (nonatomic,copy) NSString *name;@property (nonatomic,assign) int age;@end
2. Create a model object
// Create model Person * liming = [[Person alloc] init]; liming. name = @ "liming"; liming. age = 18; Person * zhangjie = [[Person alloc] init]; zhangjie. name = @ "zhangjie"; zhangjie. age = 20; Person * liuxin = [[Person alloc] init]; liuxin. name = @ "liuxin"; liuxin. age = 17; Person * wanghua = [[Person alloc] init]; wanghua. name = @ "wanghua"; wanghua. age = 16;
3. Create a storage array
// Create a storage array NSMutableArray * personArray = [inline array]; [personArray addObject: liming]; [personArray addObject: zhangjie]; [personArray addObject: liuxin]; [personArray addObject: wanghua];
4. sort by model AGE attribute
// Model sort by age attributes NSArray * ageSortResultArray = [personArray sortedArrayUsingComparator: ^ NSComparisonResult (id obj1, id obj2) {Person * per1 = obj1; Person * per2 = obj2; if (per1.age> per2.age) {return NSOrderedDescending; // descending} else if (per1.age <per2.age) {return NSOrderedAscending; // ascending} else {return NSOrderedSame; // equal}];
5. Print the result
// Print the result for (Person * per ageSortResultArray) {NSLog (@ "per. age = % d", per. age );}
6,