Our first example demonstrates sorting collections using custom comparison functions in Objective-C. We’ll explore how to sort strings by their length and custom objects by a specific property.
In this Objective-C example, we implement custom sorting for both strings and custom objects:
We start by sorting an array of fruits based on their string length. We use the sortUsingComparator: method, which takes a block that defines our custom comparison logic.
For sorting custom objects, we define a Person class with name and age properties. We then create an array of Person objects and sort them based on their age.
The sortUsingComparator: method is used again for sorting the people array. The comparator block compares the age property of two Person objects.
We use NSLog to print the sorted arrays.
To run this program, save it as a .m file (e.g., SortingByFunctions.m) and compile it using:
The output will show the sorted arrays:
This example demonstrates how to implement custom sorting logic in Objective-C, which is particularly useful when you need to sort collections based on specific criteria or properties of custom objects.