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.
You might have wrong another thing, SortDescriptors work fine with strings, here an example:
Exit in console:
I think it´s good idea to log your array before and after the sortedArrayUsingDescriptor methods.
Hi again. I´ve done the same again, with a Custom Class this is the header:
The implementation (.m) is blank, and again I´ve done:
And again, the exit console is:
There isn´t any problem with sortDescriptors and property. Best