總結OC中陣列排序3種方法

2021-09-30 11:07:56 字數 1786 閱讀 3547

大體上,oc中常用的陣列排序有以下幾種方法:sortedarrayusingselector:; 

sortedarrayusingcomparator:; 

sortedarrayusingdescriptors:

1、簡單排序(sortedarrayusingselector:)

如果只是對字串的排序,可以利用sortedarrayusingselector:方法就可以了,**如下

//簡單排序

void sortarray1()

當然,除了利用字串自帶的compare:方法,也可以自己寫compare:方法,進行物件的比較;如下:

首先是新建了person類,實現方法如下(標頭檔案就省了):

#import "person.h"

@implementation person

//直接實現靜態方法,獲取帶有name和age的person物件

+(person *)personwithage:(int) age withname:(nsstring *)name

//自定義排序方法

-(nscomparisonresult)compareperson:(person *)person

return result;

}@end

主函式**如下:

void sortarray2()
2、利用block語法(sortedarrayusingcomparator:)

蘋果官方提供了block語法,比較方便。其中陣列排序可以用sortedarrayusingcomparator:方法,**如下:

void sortarray3()];

nslog(@"排序後:%@",sortedarray);

}

3、高階排序(sortedarrayusingdescriptors:)

如果是這樣一種情況呢?person類裡有另外乙個類的變數,比如說person類除了name,age變數,還有一輛車car型別,car類裡有個name屬性。對person物件進行排序,有這樣的要求:按照car的name排序,如果是同一輛車,也就是car的name相同,那麼再按照年齡進行排序,如果年齡也相同,最後按照person的name進行排序。

上面這樣就要使用第三種方法,利用排序描述器,不多說,有興趣可以看看api介紹。**如下:

首先寫個car類,實現類car.m**如下:

#import "car.h"

@implementation car

+(car *)initwithname:(nsstring *)name

@end

然後改寫person類,實現類person.m**如下:

#import "person.h"

#import "car.h"

@implementation person

+(person *)personwithage:(int)age withname:(nsstring *)name withcar:(car *)car

//這裡重寫description方法,用於最後測試排序結果顯示

-(nsstring *)description

@end

主函式**如下:

void sortarray4()
結果如下:

從結果看出,先按照age排序,如果age相同,按照car排序,如果car相同,按照name排序。

(注意:上面兩種排序方法要想實現字串顯示,請重寫description方法)

js 陣列去重3種方法

js陣列去重的三種常用方法總結 第一種是比較常規的方法 思路 1.構建乙個新的陣列存放結果 2.for迴圈中每次從原陣列中取出乙個元素,用這個元素迴圈與結果陣列對比 3.若結果陣列中沒有該元素,則存到結果陣列中 複製 如下 array.prototype.unique1 function if re...

JQuery遍歷json陣列的3種方法

這篇文章主要介紹了jquery遍歷json陣列的3種方法,本文分別給出了使用each for遍歷json的方法,其中for又分成兩種形式,需要的朋友可以參考下 一 使用each遍歷 複製 如下 function result html 遍歷物件 each的使用 alert obj 是個object元...

CRC的3種方法

一.crc16演算法 首先在原始檔標頭檔案加入錶值 cpp view plain copy print?crc16碼表 static word const wcrc16table 256 crc16碼表 static word const wcrc16table 256 然後在檔案中加入下列函式 c...