oc中類方法中只為我們提供了一些降序方法,現在我們自己定義方法,實現公升序.
1.要求:定義乙個person類,例項變數包括name,age,height,定義幾個物件,把這些物件儲存在陣列中,自己定義方法,實現陣列按name,age,gheight的公升序排列輸出.
首先person.h檔案
#import @inte***ce person : nsobject
//初始化
- (id)initwithname:(nsstring *)name age:(nsinteger)age height:(cgfloat)height;
//姓名
- (void)setname:(nsstring *)name;
- (nsstring *)name;
//年齡
- (void)setage:(nsinteger)age;
- (nsinteger)age;
//身高
- (void)setheight:(cgfloat)height;
- (cgfloat)height;
//比較age
- (nscomparisonresult)comparebyage:(person *)anperson;
//比較身高
- (nscomparisonresult)comparebyheight:(person *)anperson;
//比較名字公升序
- (nscomparisonresult)comparebyname:(person *)anperson;
//名字降序
- (nscomparisonresult)comparebynamedesceding:(person *)anperson;
person.m檔案
#import "person.h"
@implementation person
#pragma mark - setter and getter
//set姓名
- (void)setname:(nsstring *)name
- (nsstring *)name
//set年齡
- (void)setage:(nsinteger)age
- (nsinteger)age
//set身高
- (void)setheight:(cgfloat)height
- (cgfloat)height
#pragma mark - init method
//初始化
- (id)initwithname:(nsstring *)name age:(nsinteger)age height:(cgfloat)height
return self;
}#pragma mark - override method
//重寫description
- (nsstring *)description
#pragma mark - compare
//比較年齡age
- (nscomparisonresult)comparebyage:(person *)anpersonelse if([self age] == [anperson age])else
}//比較身高
- (nscomparisonresult)comparebyheight:(person *)anpersonelse if([self height] == [anperson height])else
}//比較名字
- (nscomparisonresult)comparebyname:(person *)anperson
//名字降序
- (nscomparisonresult)comparebynamedesceding:(person *)anperson
@end
主函式中main.m呼叫
#import #import "person.h"
int main(int argc, const char * argv)
return 0;
}
測試結果:
2014-08-14 22:03:37.650 lesson_sort[4908:303] (
"name:dapeng age:30, height:190",
"name:xiaoguangguang age:20, height:180",
"name:xiaomeng age:22, height:175",
"name:xiaoshuai age:12, height:178" )
2014-08-14 22:03:37.651 lesson_sort[4908:303] (
"name:xiaoshuai age:12, height:178",
"name:xiaoguangguang age:20, height:180",
"name:xiaomeng age:22, height:175",
"name:dapeng age:30, height:190" )
2014-08-14 22:03:37.652 lesson_sort[4908:303] (
"name:xiaomeng age:22, height:175",
"name:xiaoshuai age:12, height:178",
"name:xiaoguangguang age:20, height:180",
"name:dapeng age:30, height:190" )
2014-08-14 22:03:37.652 lesson_sort[4908:303] (
"name:xiaoshuai age:12, height:178",
"name:xiaomeng age:22, height:175",
"name:xiaoguangguang age:20, height:180",
"name:dapeng age:30, height:190" )
C 的排序Sort和OrderBy擴充套件方法
可以實現乙個icomparable介面的compareto方法,或者是給予list的sort擴充套件方法,傳入委託實現,舉個例子 list.sort a,b 其實我們還可以根據orderby擴充套件方法來實現 autolist orderby a a.startswith 2 1 thenby a ...
高階shell擴充套件 sort命令
sort可針對文字檔案的內容,以行為單位來排序。sort bcdfimmnr o 輸出檔案 t 分隔字元 起始字段 結束字段 help verison 檔案 k 列數 按指定列排序。b 忽略每行前面開始出的空格字元。c 檢查檔案是否已經按照順序排序。d 排序時,處理英文本母 數字及空格字元外,忽略其...
陣列的sort 方法
sort 方法是陣列自帶的一種排序方法,預設情況下會將元素按照字串進行比較。1.當元素為字串時 將元素從字串從第一位開始比較,第一位相同時比較後一位。var arr cb a g cy arr.sort console.log arr a cb cy g 2.當元素為數字時 預設將數字元素當做字串來...