Using NSSortDescriptor to Store "nil" Values ​​at the Bottom of the List

I am working on sorting data NSFetchedResultController. I need to sort the data by their name. However, there are some records without a name.

I need the "untitled" objects to appear at the bottom of the list, and not at the top. With the current code, when I sort the list by name, the cells "no first name" are placed at the top.

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Contacts"];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES]];
_FRC = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                            managedObjectContext:MOC
                                           sectionNameKeyPath:nil cacheName:nil];   
_FRC.delegate = self;
+3
source share
2 answers

Update after some consultation with colleagues :)

-, "", "nil", ?

, , , BOOL, hasFirstName, hasFirstName, firstName.

+5

NSSortDescriptor sortDescriptorWithKey:ascending:comparator:. , . :

^NSComparisonResult(NSString *obj1, NSString *obj2) {
     if (obj1.length == 0) {
         return NSOrderedDescending;
     }
     if (obj2.length == 0) {
         return NSOrderedAscending;
     }

     return [obj1 compare:obj2];
 }
-1

Source: https://habr.com/ru/post/1526190/


All Articles