I’m currently trying to teach myself Objective-C and was playing around with an exercise where I needed to sort an array.
I managed to complete it using the following code:
NSSortDescriptor * newSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:TRUE];
NSArray *sortDescriptors = [NSArray arrayWithObject:newSortDescriptor];
[self.theBookStore sortUsingDescriptors:sortDescriptors];
My question is about what is actually happening here. I don’t really understand exactly what I’ve done.
Line 1: I understand here I’ve created a new object that has a descriptor. This has two parameters, the column I want to sort on and that it is ascending.
Line 2: This is the line I’m confused about. Why do I need an array of sort descriptors? When I read this code I suspect it creates an array with only one row is that correct?
Line 3: I understand that this is calling the sortUsingDescriptors method but again, my confusion is why this function expects an array.
I’ve read the documentation but I’m really looking for a simple explanation.
Any help is much appreciated
Line 1: .. yes your right. You are creating a custom object called
NSSortDescriptor. That object defines a attribute to sort after. You did enter “title”. So the objects in your array-to-sort will be sorted after that property (yourObject.title “kind-of”).Line 2: Because the sorting method (
sortUsingDescriptors) always needs a array, you need to create a NSArray with only one object. Okay, … looks kind of stupid. But makes absolute sense. Lets say you would like to sort after two criteria (lets say “title”, then “city”).Line 3: Yes heres must be a array because of sorting after more then one criteria.
And always keep the memory clean:
On line 1 you did allocate/init a NSSortDescriptor.
So clean up after using it (if you are not using ARC).
So add a line: