Re: Sorting array of strings by string length
Re: Sorting array of strings by string length
- Subject: Re: Sorting array of strings by string length
- From: Greg Herlihy <email@hidden>
- Date: Mon, 20 Feb 2006 16:50:49 -0800
- Thread-topic: Sorting array of strings by string length
I think a slightly more flexible (and more simple) solution would be to
implement the necessary sortable selector in NSString itself:
@interface NSString(MyAdditions)
-(id)lengthAsNumber;
@end
@implementation NSString(MyAdditions)
-(id)lengthAsNumber
{
return [NSNumber numberWithUnsignedInt:[self length]];
}
@end
Now the program can simply call sortedArrayUsingSelector to obtain a sorted
array - just as it originally wanted to do:
NSArray *sortedArray;
sortedArray = [array sortedArrayUsingSelector:@selector(lengthAsNumber)];
Greg
On 2/20/06 3:01 PM, "Scott Anguish" <email@hidden> wrote:
> ah, yes.. thanks for the clarification... I even thought about that
> before I wrote it, and still didn't
>
> as penance.. from the doc (although modified slightly)
>
> you'd want to add a compareByLength:(NSString *)aString method to
> NSString, that accepts a string as a parameter, and returns a
> (NSComparisonResult) that indicates the ordering of the two items.
>
> Returns NSOrderedAscending if the string of the receiver precedes
> aString in lexical ordering, NSOrderedSame if the string of the
> receiver and aString are equivalent in lexical value, and
> NSOrderedDescending if the string of the receiver follows aString.
>
>
>
> On Feb 20, 2006, at 5:55 PM, Prachi Gauriar wrote:
>
>>
>> On Feb 20, 2006, at 5:49 PM, Scott Anguish wrote:
>>
>>> On Feb 20, 2006, at 5:42 PM, Nik Youdale wrote:
>>>> How would i go about sorting an array of strings in ascending/
>>>> descending order of string lengths. Is there an easy way to do
>>>> this, like using something like:
>>>>
>>>> [array sortedArrayUsingSelector:@selector
>>>> (caseInsensitiveCompare:)], is there a different selector i could
>>>> put in there that would sort the array by string length?
>>>
>>> you'd need to write your own sort method to use with it, but it's
>>> pretty easy.
>>>
>>> You'd add a category to the objects you want to sort.
>>
>> And by sort method, Scott meant compare method (comparator).
>>
>> -Prachi
>
> _______________________________________________
> Do not post admin requests to the list. They will be ignored.
> Cocoa-dev mailing list (email@hidden)
> Help/Unsubscribe/Update your Subscription:
>
> This email sent to email@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden