Pregunta

Newbie Question,

I am playing with NSMutableArray *myBook that contains card elements (name and email address).

I want myBook displayed with descending list.

AddressBook.h

#import <Foundation/Foundation.h>
#import "AddressCard.h"
@interface AddressBook : NSObject

@property (nonatomic, copy) NSMutableString *bookName;

@property (nonatomic , strong) NSMutableArray *book;

AddressCard.h

#import <Foundation/Foundation.h>

@interface AddressCard : NSObject

@property (nonatomic, copy) NSMutableString *name, *email;

AddressBook.m

- (void) sort{
    [book sortUsingSelector:@selector(compareNames:)];
}

- (void) showList{

    NSLog(@"====== Contents of: %@ =======",bookName);


    for (AddressCard *theCard in book) {
        NSLog(@"%-20s    %-32s", [theCard.name UTF8String], [theCard.email UTF8String] );
    }

    NSLog(@"===============================");
}

AddressCard.m

- (NSComparisonResult) compareNames: (id) element{


    return [name compare:[element name]];
}

my CompareNames method returns Ascending result. How do I make it to return Descending?

Thanks !

¿Fue útil?

Solución

while - (void)sortUsingSelector:(SEL)comparator method suppose to sorts the array's elements in ascending order, the comparator method should return NSOrderedAscending if the array is smaller than the argument, NSOrderedDescending if the array is larger than the argument, and NSOrderedSame if they are equal.

Since the NSComparisonResult define as:

enum {
   NSOrderedAscending = -1,
   NSOrderedSame,
   NSOrderedDescending
};

typedef NSInteger NSComparisonResult;

All you need is a descendingComparator, something like:

- (NSComparisonResult)compareNameInDesendingOrder:(AddressCard *)aCard {
    return -[self.name compare:[aCard name]];
}

- (void)sortInDesendingOrder {
    [book sortUsingSelector:@selector(compareNameInDesendingOrder:)];
}

hope it helps.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top