I've created simple class Student with properties
@property (strong,nonatomic) NSString* firstname;
@property (strong,nonatomic) NSString* lastname;
@property (strong,nonatomic) NSDate* dateOfBirth;
@property (assign,nonatomic) NSInteger index;
After that, I created any objects of this class, gave it firstname, lastname, date and index, add all of them to self.InitialStudentsArray. And start sorting by dateOfBirth:
NSSortDescriptor* descriptorDate=[[NSSortDescriptor alloc]initWithKey:@"dateOfBirth" ascending:YES];
NSArray* descArray=[NSArray arrayWithObjects:descriptorDate, nil];
[self.InitialStudentsArray sortUsingDescriptors:descArray];
So, the result is strange. Array before sorting and after sorting have different items order, but not sorted at all by date.
before sort (
"46 Alex Dupel 25 10 1991",
"236 Ivan Evstegneev 20 09 1980",
"179 Hugo Igonin 03 02 1992",
"189 Alexey Boronenko 06 11 1978" )
after sort (
"236 Ivan Evstegneev 20 09 1980",
"179 Hugo Igonin 03 02 1992",
"189 Alexey Boronenko 06 11 1978",
"46 Alex Dupel 25 10 1991" )
The same thing with firstname and lastname (even if use selectors:
NSSortDescriptor* descriptorLastname=[[NSSortDescriptor alloc]initWithKey:@"lastname" ascending:YES selector:@selector(caseInsensitiveCompare:)];
It's only work for property "index",which is NSInteger.
What I've done else, I created array only with dates from student.dateOfBirth and sorted it with keyname self. And it works! Another experiment - I created array of dictionaries with key "dateOfBirth" and sorted it by key name @"dateOfBirth" and it also works!
I know about other methods live sortUsingComparator, but why this method doesn't work on date and strings in properties??
Upd Oh, guys, it's my mistake. I appreciate all of your answers, they pushed me to place, where to search mistake. And when I found it, I felt very ashamed. Absolutly stupid mistake. If you are interested in, I used this way to initialize student:
- (instancetype)init
{
self = [super init];
if (self) {
self.firstname=[self getFirstname];
self.lastname=[self getLastname];
self.dateOfBirth=[self getDateOfBirth];
}
return self;
}
-(NSString*) getFirstname {//some code...arrayOfFirstames...name=arc4random()...}
I.e. I occasionally redefine getter for setting property. All three. So, when I was sorting array everytime new values was taken. Thank you.
firstname
with descending order. You should change your date format if you want it to sort correctly using string comparison. Instead of "DD MM YYYY" use "YYYY MM DD". – Ian MacDonald[descriptorDate compareObject:self.InitialStudentsArray[0] toObject:self.InitialStudensArray[1]]
, does it return the correct value? – Ian MacDonald