I was having some confusion when the book started talking about alphabetizing elements in the array using the sort and compareNames: method. How is the argument for compareNames obtained when the method sort is called? And how do the elements actually get alphabetize when all that’s returned is a type of NSComparisonResult?
#import <Foundation/Foundation.h>
@interface AddressCard : NSObject
@property (copy, nonatomic) NSString *name, *email;
-(NSComparisonResult) compareNames: (id) element;
@end
@implementation AddressCard
@synthesize name, email;
-(NSComparisonResult) compareNames:(id)element {
return [name compare: [element name]];
}
@end
#import "AddressCard.h"
#import <Foundation/Foundation.h>
@interface AddressBook : NSObject
@property (nonatomic, copy) NSString *bookName;
@property (nonatomic, strong) NSMutableArray *book;
-(void) addCard: (AddressCard *) myCard;
-(void) sort;
@end
@implementation AddressBook
@synthesize book, bookName;
-(void) sort {
[book sortUsingSelector: @selector(compareNames:)];
}
A
NSComparisonResultis just one ofNSOrderedAscending,NSOrderedSame,NSOrderedDescending.The method
compareNamesis responsible of the true comparison. In this case, since you are comparing strings, the method just rely on already-implementedcomparemethod ofNSString. The result gives information about the comparison between two strings according to the alphabetical order.Method
sortUsingSelectorofNSMutableArrayis a useful method to sort custom types of data (you can appreciate better if you try to sort custom objects according to custom criteria). It accepts a selector, which means that every time it needs to compare two object, the method specified by the selector is called.For what I remember you are not allowed to know the method
sortUsingSelectorinternally uses (quick sort / heap sort / bubble sort…), what you need to know is that object are ordered using the criteria specified by the implementation of the method you pass with the selector.