iOS基礎知識之排序

來源:互聯網
上載者:User

標籤:style   sort   iso   selector   rest   cto   sar   sam   str   

1.字串比較

1 - (NSComparisonResult)compare:(NSString *)str;

例如:

1 NSString *str1 = @"zhangsan";2 NSString *str2 = @"susan";3 NSComparisonResult result = [str1 compare:str2];

 

2.數組的自訂排序

1 NSArray *arr = [NSArray array];2 [arr sortUsingSelector:@selector(自訂的比較方法)];

此處自訂的比較方法參照NSString中compare:方法進行設計。
例如設計一個Student類,其中包含name和age兩個屬性,若設計按照年齡進行比較的方法,則代碼如下:

代碼聲明為:

1 - (NSComparisonResult)compareStudent:(Student *)s;

代碼實現為:

1 - (NSComparisonResult)compareStudent:(Student *)s {2     if(self.age > s.age){3         return NSOrderedDescending;4     }else if(self.age < s.age) {5         return NSOrderedAscending;6     }else{7         return NSOrderedSame;8     }9 }

注意:上述方法的聲明和實現全是在Student類中實現。
調用比較方法的代碼為:

1 [arr sortUsingSelector:@selector(compareStudent:)];//arr中存放了n個student對象

 

3.多屬性比較的數組排序

1 //描述器:第一個參數表示待比較的屬性名稱,第二個參數為YSE表示為升序,否則為降序2 NSSortDescriptor *ageDes = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];3 NSSortDescriptor *nameDes = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];4 [arr sortUsingDescriptors:@[ageDes,nameDes]];//表示先按照年齡排序,然後按照名字排序

 

iOS基礎知識之排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.