Array Sorting in Objective-C

I'm currently trying to teach myself Objective-C and was playing with an exercise where I needed to sort an array.

I managed to populate 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 what is really going on here. I do not quite understand what I did.

Line 1: I understand, here I created a new object with a descriptor. It has two parameters, the column that I want to sort, and that it goes back.

Line 2: This is the line that I am confused about. Why do we need an array of sort descriptors? When I read this code, I suspect that it creates an array with only one row, which is correct?

Line 3: I understand that this is a call to the sortUsingDescriptors method, but again, my confusion is why this function expects an array.

I read the documentation, but I'm really looking for a simple explanation.

+3
3
  • 1:.. , . NSSortDescriptor. . "". , (yourObject.title "-of" ).

  • 2: (sortUsingDescriptors) , NSArray . ,... . . , (, "title", "city" ).

  • 3: , - .

: 1 /init NSSortDescriptor. ( ARC). :

[newSortDescriptor release];
+2

1: , , . : , , .

, , . , .

2: , . ? , , ?

- , . , . , , , . , , , . , , , .

3: , sortUsingDescriptors , , , .

, , , ( ..) . , , . NSArray , , :

@category NSArray (SingleSortDescriptor)

- (NSArray*)sortUsingDescriptor:(NSSortDescriptor*)descriptor;

@end

@implementation NSArray (SingleSortDescriptor)

- (NSArray*)sortUsingDescriptor:(NSSortDescriptor*)descriptor
{
    return [self sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];
}

@end
+5

Multiple sort descriptors will be used to resolve what happens if there are multiple matches. I have a priority order. The second descriptor will tell you what to do if he finds two headers the same.

+1
source

All Articles