Re: - (void)sortUsingSelector:(SEL)comparator
Re: - (void)sortUsingSelector:(SEL)comparator
- Subject: Re: - (void)sortUsingSelector:(SEL)comparator
- From: "Dennis C. De Mars" <email@hidden>
- Date: Wed, 25 Jul 2001 17:58:51 -0000
peter mysliwy <email@hidden> said:
>
Hello;
>
I am new to apple and ObjectiveC and started by playing around with
>
NSArray and NSMutableArray to learn something about the native datatypes.
>
>
The question I have How do I sort a NSArray using
>
- (void)sortUsingSelector:(SEL)comparator
>
>
What does (SEL)comparator mean??
>
>
From what I can figure out is that comparator is a switch. Any Info??
SEL is the type of a selector, which is the term for the messages you send to an
object. See the objc.pdf manual for more information, but I'll give an example.
Selectors can be passed just like functions. In this case, the NSMutableArray info says
the selector will be sent to an object in your array, take another object of the same
type as an argument, and return a value of type NSComparisonResult. (See the
NSMutableArray documetnation for more info on this).
Now, I was going to give an example with an array of integers, using NSValue to hold
the integers, but oddly enough NSValue doesn't have a comparison method of this type.
We could add one with a category, but instead I'll use NSString as an example, since it
does have such a comparison method:
- (NSComparisonResult)compare:(NSString *)aString
OK, suppose we have an NSMutableArray object called myStringArray that has a bunch of
NSString objects as its elements. To sort this, you would do the following:
[myStringArray sortUsingSelector: @selector(compare:)];
The @selector is a compiler directive (described in the Obj-C manual) that takes the
name of the selector as an argument and returns a value of type SEL which is the
internal Objective C representation of the selector. You always have to use it when you
are passing selectors as arguments. Note that in "compare:" the colon is part of the
selector name.
When you are sorting an array and the elements already have a comparison method, this
is a handy way of sorting them. If you are sorting elements that don't have such a
comparison method, you can define a function to compare them and sort using
the "sortUsingFunction:" method instead (or, as I said before, you can add a comparison
method to the class in question using a category, then you could use
sortUsingSelector:).
- Dennis D.