Jak posortować NSMutableArray z obiektami niestandardowymi?
To, co chcę zrobić, wydaje się dość proste, ale nie mogę znaleźć żadnych odpowiedzi w Internecie. Mam NSMutableArray
obiektów i powiedzmy, że są to obiekty "osobowe". Chcę posortować NSMutableArray
Według osoby.data urodzenia, która jest NSDate
.
Myślę, że ma to coś wspólnego z tą metodą:
NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(???)];
W Javie chciałbym, aby mój obiekt implementował porównywalne, lub używał kolekcji.Sortuj za pomocą wbudowanego komparatora niestandardowego...jak to robisz w Objective-C?
25 answers
Metoda porównania
Albo zaimplementujesz metodę porównywania dla swojego obiektu:
- (NSComparisonResult)compare:(Person *)otherObject {
return [self.birthDate compare:otherObject.birthDate];
}
NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];
NSSortDescriptor (lepszy)
Lub Zwykle jeszcze lepiej:
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES];
NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];
Można łatwo sortować według wielu kluczy, dodając więcej niż jeden do tablicy. Możliwe jest również użycie niestandardowych metod porównawczych. Zapoznaj się z dokumentacją.
Klocki (błyszczące!)
Istnieje również możliwość sortowania z blokiem od Mac OS X 10.6 i iOS 4:
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSDate *first = [(Person*)a birthDate];
NSDate *second = [(Person*)b birthDate];
return [first compare:second];
}];
Wydajność
Metody -compare:
i blokowe będą ogólnie nieco szybsze niż NSSortDescriptor
, ponieważ ta ostatnia opiera się na KVC. Główną zaletą metody NSSortDescriptor
jest to, że zapewnia sposób definiowania kolejności sortowania za pomocą danych, a nie kodu, co ułatwia np. konfigurowanie rzeczy, aby użytkownicy mogli sortować NSTableView
, klikając wiersz nagłówka.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-12 14:50:16
Zobacz metodę NSMutableArray
sortUsingFunction:context:
Będziesz musiał ustawić compare funkcję, która pobiera dwa obiekty (typu Person
, ponieważ porównujesz dwa obiekty Person
) i parametr context .
Oba obiekty są tylko instancjami Person
. Trzecim obiektem jest łańcuch znaków, np. @ "birthDate".
Ta funkcja zwraca NSComparisonResult
: zwraca NSOrderedAscending
jeśli PersonA.birthDate
PersonB.birthDate. Zwróci NSOrderedDescending
jeśli PersonA.birthDate
> PersonB.birthDate
. Na koniec zwróci NSOrderedSame
, Jeśli PersonA.birthDate
== PersonB.birthDate
.
Jest to szorstki pseudokod; musisz uformować, co to znaczy, aby jedna data była "mniej"," więcej "lub" równa " innej dacie (np. porównując seconds-since-epoch itp.):
NSComparisonResult compare(Person *firstPerson, Person *secondPerson, void *context) {
if ([firstPerson birthDate] < [secondPerson birthDate])
return NSOrderedAscending;
else if ([firstPerson birthDate] > [secondPerson birthDate])
return NSOrderedDescending;
else
return NSOrderedSame;
}
Jeśli chcesz czegoś bardziej kompaktowego, możesz użyć operatorów trójdzielnych:
NSComparisonResult compare(Person *firstPerson, Person *secondPerson, void *context) {
return ([firstPerson birthDate] < [secondPerson birthDate]) ? NSOrderedAscending : ([firstPerson birthDate] > [secondPerson birthDate]) ? NSOrderedDescending : NSOrderedSame;
}
Inlining może to trochę przyspieszyć, jeśli robisz to często.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-13 17:21:52
Zrobiłem to w iOS 4 używając bloku. Musiałem przerzucić elementy tablicy z id na typ mojej klasy. W tym przypadku była to klasa o nazwie Score z właściwością o nazwie punkty.
Musisz również zdecydować, co zrobić, jeśli elementy tablicy nie są odpowiednim typem, w tym przykładzie zwróciłem NSOrderedSame
, jednak w moim kodzie pomyślałem o wyjątku.
NSArray *sorted = [_scores sortedArrayUsingComparator:^(id obj1, id obj2){
if ([obj1 isKindOfClass:[Score class]] && [obj2 isKindOfClass:[Score class]]) {
Score *s1 = obj1;
Score *s2 = obj2;
if (s1.points > s2.points) {
return (NSComparisonResult)NSOrderedAscending;
} else if (s1.points < s2.points) {
return (NSComparisonResult)NSOrderedDescending;
}
}
// TODO: default is the same?
return (NSComparisonResult)NSOrderedSame;
}];
return sorted;
PS: to sortowanie w porządku malejącym.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-03 07:22:00
Począwszy od iOS 4 Możesz również używać bloków do sortowania.
W tym przykładzie zakładam, że obiekty w tablicy mają metodę 'position', która zwraca NSInteger
.
NSArray *arrayToSort = where ever you get the array from... ;
NSComparisonResult (^sortBlock)(id, id) = ^(id obj1, id obj2)
{
if ([obj1 position] > [obj2 position])
{
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 position] < [obj2 position])
{
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
};
NSArray *sorted = [arrayToSort sortedArrayUsingComparator:sortBlock];
Uwaga: tablica" posortowana " zostanie automatycznie dodana.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-13 09:52:16
Próbowałem wszystkiego, ale to mi pomogło. W klasie mam inną klasę o nazwie " crimeScene
" i chcę sortować według właściwości " crimeScene
".
To działa jak urok:
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"crimeScene.distance" ascending:YES];
[self.arrAnnotations sortUsingDescriptors:[NSArray arrayWithObject:sorter]];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-24 07:40:28
W drugiej odpowiedzi Georga Schölly ' ego brakuje kroku, ale wtedy działa dobrze.
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptor:sortDescriptors];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:39
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate" ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];
Dzięki, działa dobrze...Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-31 18:00:00
Twoje obiekty Person
muszą zaimplementować metodę, powiedzmy compare:
, która pobiera inny obiekt Person
i zwraca NSComparisonResult
zgodnie z relacją między dwoma obiektami.
Wtedy zadzwoniłbyś sortedArrayUsingSelector:
z @selector(compare:)
i powinno być zrobione.
Są inne sposoby, ale z tego co wiem, nie ma Cocoa-equiv interfejsu Comparable
. Używanie sortedArrayUsingSelector:
jest prawdopodobnie najbardziej bezbolesnym sposobem na to.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-04-30 06:25:14
IOS 4 bloki Cię uratują:)
featuresArray = [[unsortedFeaturesArray sortedArrayUsingComparator: ^(id a, id b)
{
DMSeatFeature *first = ( DMSeatFeature* ) a;
DMSeatFeature *second = ( DMSeatFeature* ) b;
if ( first.quality == second.quality )
return NSOrderedSame;
else
{
if ( eSeatQualityGreen == m_seatQuality || eSeatQualityYellowGreen == m_seatQuality || eSeatQualityDefault == m_seatQuality )
{
if ( first.quality < second.quality )
return NSOrderedAscending;
else
return NSOrderedDescending;
}
else // eSeatQualityRed || eSeatQualityYellow
{
if ( first.quality > second.quality )
return NSOrderedAscending;
else
return NSOrderedDescending;
}
}
}] retain];
Http://sokol8.blogspot.com/2011/04/sorting-nsarray-with-blocks.html trochę opisu
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-08 12:21:10
Dla NSMutableArray
użyj metody sortUsingSelector
. Sortuje it-place, bez tworzenia nowej instancji.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-03 07:23:14
Możesz użyć poniższej metody ogólnej do swojego celu. To powinno rozwiązać twój problem.
//Called method
-(NSMutableArray*)sortArrayList:(NSMutableArray*)arrDeviceList filterKeyName:(NSString*)sortKeyName ascending:(BOOL)isAscending{
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:sortKeyName ascending:isAscending];
[arrDeviceList sortUsingDescriptors:[NSArray arrayWithObject:sorter]];
return arrDeviceList;
}
//Calling method
[self sortArrayList:arrSomeList filterKeyName:@"anything like date,name etc" ascending:YES];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-29 20:56:35
Jeśli sortujesz tablicę NSNumbers
, możesz je sortować za pomocą 1 wywołania:
[arrayToSort sortUsingSelector: @selector(compare:)];
To działa, ponieważ obiekty w tablicy (NSNumber
objects) implementują metodę compare. To samo można zrobić dla obiektów NSString
, a nawet dla tablicy niestandardowych obiektów danych, które implementują metodę porównywania.
Oto przykładowy kod wykorzystujący bloki komparatora. Sortuje tablicę słowników, gdzie każdy słownik zawiera liczbę w kluczu "sort_key".
#define SORT_KEY @\"sort_key\"
[anArray sortUsingComparator:
^(id obj1, id obj2)
{
NSInteger value1 = [[obj1 objectForKey: SORT_KEY] intValue];
NSInteger value2 = [[obj2 objectForKey: SORT_KEY] intValue];
if (value1 > value2)
{
return (NSComparisonResult)NSOrderedDescending;
}
if (value1 < value2)
{
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
Kod powyżej omówiono pracę polegającą na pobraniu wartości całkowitej dla każdego klucza sortowania i porównaniu ich jako ilustracji, jak to zrobić. Ponieważ obiektyNSNumber
implementują metodę porównywania, można ją przepisać znacznie prościej:
#define SORT_KEY @\"sort_key\"
[anArray sortUsingComparator:
^(id obj1, id obj2)
{
NSNumber* key1 = [obj1 objectForKey: SORT_KEY];
NSNumber* key2 = [obj2 objectForKey: SORT_KEY];
return [key1 compare: key2];
}];
Lub korpus komparatora może być nawet destylowany do 1 linii:
return [[obj1 objectForKey: SORT_KEY] compare: [obj2 objectForKey: SORT_KEY]];
Preferuję proste instrukcje i wiele zmiennych tymczasowych, ponieważ kod jest łatwiejszy do odczytania i łatwiejszy do debugowania. Kompilator optymalizuje tymczasowe zmienne w każdym razie, więc nie ma korzyści dla wersji all-in-one-line.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-03 07:22:57
Stworzyłem małą bibliotekę metod kategorii, nazwaną Linq to ObjectiveC , która ułatwia tego typu rzeczy. Używając metody sort z selektorem klawiszy, możesz sortować według birthDate
w następujący sposób:
NSArray* sortedByBirthDate = [input sort:^id(id person) {
return [person birthDate];
}]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-06 08:29:13
Właśnie zrobiłem sortowanie wielopoziomowe w oparciu o niestandardowe wymagania.
/ / Sortuj wartości
[arrItem sortUsingComparator:^NSComparisonResult (id a, id b){
ItemDetail * itemA = (ItemDetail*)a;
ItemDetail* itemB =(ItemDetail*)b;
//item price are same
if (itemA.m_price.m_selling== itemB.m_price.m_selling) {
NSComparisonResult result= [itemA.m_itemName compare:itemB.m_itemName];
//if item names are same, then monogramminginfo has to come before the non monograme item
if (result==NSOrderedSame) {
if (itemA.m_monogrammingInfo) {
return NSOrderedAscending;
}else{
return NSOrderedDescending;
}
}
return result;
}
//asscending order
return itemA.m_price.m_selling > itemB.m_price.m_selling;
}];
Https://sites.google.com/site/greateindiaclub/mobil-apps/ios/multilevelsortinginiosobjectivec
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-13 03:06:46
Użyłem sortUsingFunction:: w niektórych moich projektach:
int SortPlays(id a, id b, void* context)
{
Play* p1 = a;
Play* p2 = b;
if (p1.score<p2.score)
return NSOrderedDescending;
else if (p1.score>p2.score)
return NSOrderedAscending;
return NSOrderedSame;
}
...
[validPlays sortUsingFunction:SortPlays context:nil];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-31 18:00:53
-(NSMutableArray*) sortArray:(NSMutableArray *)toBeSorted
{
NSArray *sortedArray;
sortedArray = [toBeSorted sortedArrayUsingComparator:^NSComparisonResult(id a, id b)
{
return [a compare:b];
}];
return [sortedArray mutableCopy];
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-11 11:32:29
Sortowanie NSMutableArray
jest bardzo proste:
NSMutableArray *arrayToFilter =
[[NSMutableArray arrayWithObjects:@"Photoshop",
@"Flex",
@"AIR",
@"Flash",
@"Acrobat", nil] autorelease];
NSMutableArray *productsToRemove = [[NSMutableArray array] autorelease];
for (NSString *products in arrayToFilter) {
if (fliterText &&
[products rangeOfString:fliterText
options:NSLiteralSearch|NSCaseInsensitiveSearch].length == 0)
[productsToRemove addObject:products];
}
[arrayToFilter removeObjectsInArray:productsToRemove];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-31 18:02:06
Sortuj za pomocą NSComparator
Jeśli chcemy sortować obiekty niestandardowe, musimy podać NSComparator
, która jest używana do porównywania obiektów niestandardowych. Blok Zwraca wartość NSComparisonResult
, która określa kolejność obu obiektów. Tak więc w celu sortowania całej tablicy NSComparator
jest używana w następujący sposób.
NSArray *sortedArray = [employeesArray sortedArrayUsingComparator:^NSComparisonResult(Employee *e1, Employee *e2){
return [e1.firstname compare:e2.firstname];
}];
Sortowanie Za Pomocą NSSortDescriptor
Załóżmy, jako przykład, że mamy tablicę zawierającą instancje klasy niestandardowej, która ma atrybuty firstname, lastname i wieku. Poniższy przykład ilustruje jak utworzyć nssortdescriptor, który może być użyty do sortowania zawartości tablicy w kolejności rosnącej według klucza age.
NSSortDescriptor *ageDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
NSArray *sortDescriptors = @[ageDescriptor];
NSArray *sortedArray = [employeesArray sortedArrayUsingDescriptors:sortDescriptors];
Sortuj za pomocą własnych porównań
Nazwy są ciągami znaków, a kiedy sortujesz ciągi znaków do przedstawienia Użytkownikowi, zawsze powinieneś użyć lokalnego porównania. Często chcesz również przeprowadzić porównanie wielkości liter. Oto przykład z (localizedStandardCompare:) aby uporządkować tablicę według last I first nazwisko.
NSSortDescriptor *lastNameDescriptor = [[NSSortDescriptor alloc]
initWithKey:@"lastName" ascending:YES selector:@selector(localizedStandardCompare:)];
NSSortDescriptor * firstNameDescriptor = [[NSSortDescriptor alloc]
initWithKey:@"firstName" ascending:YES selector:@selector(localizedStandardCompare:)];
NSArray *sortDescriptors = @[lastNameDescriptor, firstNameDescriptor];
NSArray *sortedArray = [employeesArray sortedArrayUsingDescriptors:sortDescriptors];
W celach informacyjnych i szczegółowej dyskusji proszę odnieść się:
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html
http://www.ios-blog.co.uk/tutorials/objective-c/how-to-sort-nsarray-with-custom-objects/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-17 05:12:49
Protokoły Swifta i programowanie funkcjonalne sprawiają, że jest to bardzo proste, wystarczy, że twoja klasa będzie zgodna z porównywalnym protokołem, zaimplementuje metody wymagane przez protokół, a następnie użyje funkcji sorted (by: ) high order, aby utworzyć posortowaną tablicę bez konieczności używania mutowalnych tablic przy okazji.
class Person: Comparable {
var birthDate: NSDate?
let name: String
init(name: String) {
self.name = name
}
static func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.birthDate === rhs.birthDate || lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedSame
}
static func <(lhs: Person, rhs: Person) -> Bool {
return lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedAscending
}
static func >(lhs: Person, rhs: Person) -> Bool {
return lhs.birthDate?.compare(rhs.birthDate as! Date) == .orderedDescending
}
}
let p1 = Person(name: "Sasha")
p1.birthDate = NSDate()
let p2 = Person(name: "James")
p2.birthDate = NSDate()//he is older by miliseconds
if p1 == p2 {
print("they are the same") //they are not
}
let persons = [p1, p2]
//sort the array based on who is older
let sortedPersons = persons.sorted(by: {$0 > $1})
//print sasha which is p1
print(persons.first?.name)
//print James which is the "older"
print(sortedPersons.first?.name)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-27 22:14:35
W moim przypadku używam "sortedArrayUsingComparator"do sortowania tablicy. Spójrz na poniższy kod.
contactArray = [[NSArray arrayWithArray:[contactSet allObjects]] sortedArrayUsingComparator:^NSComparisonResult(ContactListData *obj1, ContactListData *obj2) {
NSString *obj1Str = [NSString stringWithFormat:@"%@ %@",obj1.contactName,obj1.contactSurname];
NSString *obj2Str = [NSString stringWithFormat:@"%@ %@",obj2.contactName,obj2.contactSurname];
return [obj1Str compare:obj2Str];
}];
Również moim przedmiotem jest,
@interface ContactListData : JsonData
@property(nonatomic,strong) NSString * contactName;
@property(nonatomic,strong) NSString * contactSurname;
@property(nonatomic,strong) NSString * contactPhoneNumber;
@property(nonatomic) BOOL isSelected;
@end
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-28 14:00:21
Sort Array In Swift
Dla Swifty
Osoby poniżej jest bardzo czystą techniką, aby osiągnąć powyższy cel na całym świecie. Pozwala mieć przykładową klasę User
, która ma pewne atrybuty.
class User: NSObject {
var id: String?
var name: String?
var email: String?
var createdDate: Date?
}
Teraz mamy tablicę, którą musimy posortować na podstawie createdDate
rosnąco i / lub malejąco. Więc pozwala dodać funkcję do porównania daty.
class User: NSObject {
var id: String?
var name: String?
var email: String?
var createdDate: Date?
func checkForOrder(_ otherUser: User, _ order: ComparisonResult) -> Bool {
if let myCreatedDate = self.createdDate, let othersCreatedDate = otherUser.createdDate {
//This line will compare both date with the order that has been passed.
return myCreatedDate.compare(othersCreatedDate) == order
}
return false
}
}
Teraz mamy extension
z Array
dla User
. W prostych słowach pozwala dodać kilka metod tylko dla tych tablic które mają w sobie tylko User
obiekty.
extension Array where Element: User {
//This method only takes an order type. i.e ComparisonResult.orderedAscending
func sortUserByDate(_ order: ComparisonResult) -> [User] {
let sortedArray = self.sorted { (user1, user2) -> Bool in
return user1.checkForOrder(user2, order)
}
return sortedArray
}
}
Użycie dla porządku rosnącego
let sortedArray = someArray.sortUserByDate(.orderedAscending)
Użycie dla porządku malejącego
let sortedArray = someArray.sortUserByDate(.orderedAscending)
Użycie dla tego samego zamówienia
let sortedArray = someArray.sortUserByDate(.orderedSame)
Powyższa metoda w
extension
będzie dostępna tylko wtedy, gdy {[10] } jest typu[User]
||Array<User>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-24 21:20:34
Musisz utworzyć sortDescriptor, a następnie możesz posortować nsmutablearray za pomocą sortDescriptor jak poniżej.
let sortDescriptor = NSSortDescriptor(key: "birthDate", ascending: true, selector: #selector(NSString.compare(_:)))
let array = NSMutableArray(array: self.aryExist.sortedArray(using: [sortDescriptor]))
print(array)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-12 10:32:49
Używasz NSSortDescriptor do sortowania NSMutableArray z obiektami niestandardowymi
NSSortDescriptor *sortingDescriptor;
sortingDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES];
NSArray *sortArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-14 09:21:27
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"_strPrice"
ascending:sortFlag selector:@selector(localizedStandardCompare:)] ;
NSMutableArray *stockHoldingCompanies = [NSMutableArray arrayWithObjects:fortune1stock,fortune2stock,fortune3stock,fortune4stock,fortune5stock,fortune6stock , nil];
NSSortDescriptor *sortOrder = [NSSortDescriptor sortDescriptorWithKey:@"companyName" ascending:NO];
[stockHoldingCompanies sortUsingDescriptors:[NSArray arrayWithObject:sortOrder]];
NSEnumerator *enumerator = [stockHoldingCompanies objectEnumerator];
ForeignStockHolding *stockHoldingCompany;
NSLog(@"Fortune 6 companies sorted by Company Name");
while (stockHoldingCompany = [enumerator nextObject]) {
NSLog(@"===============================");
NSLog(@"CompanyName:%@",stockHoldingCompany.companyName);
NSLog(@"Purchase Share Price:%.2f",stockHoldingCompany.purchaseSharePrice);
NSLog(@"Current Share Price: %.2f",stockHoldingCompany.currentSharePrice);
NSLog(@"Number of Shares: %i",stockHoldingCompany.numberOfShares);
NSLog(@"Cost in Dollars: %.2f",[stockHoldingCompany costInDollars]);
NSLog(@"Value in Dollars : %.2f",[stockHoldingCompany valueInDollars]);
}
NSLog(@"===============================");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-07 23:26:05