Re: Sorting
Re: Sorting
- Subject: Re: Sorting
- From: "Stan Soria" <email@hidden>
- Date: Wed, 16 Feb 2005 16:31:05 -0800
- Organization: 36N 121W
Peter,
I use a category called "NSString_ODCompareNumerically" by Norbert Heger
of Objective Development to sort alphanumeric strings. Seems to works
fine with your example, too.
See this thread for code and discussion:
<http://www.cocoabuilder.com/archive/message/cocoa/2002/1/16/61373>
stan
Peter Karlsson < email@hidden >wrote on 2/16/05:
>It seems that I'm doing something wrong here. This will not sort
>numerically.
>
>The result is:
>
>aaa10
>aaa14
>aaa15
>aaa2
>
>But I want it to be:
>
>aaa2
>aaa10
>aaa14
>aaa15
>
>What am I doing wrong?
>
> NSMutableArray *arr = [NSMutableArray array];
>
> NSMutableDictionary *dic1 = [NSMutableDictionary
>dictionaryWithObjectsAndKeys:@"aaa10",@"key1",@"bbb1",@"key2",@"ccc1",@"key3
>",nil];
> NSMutableDictionary *dic2 = [NSMutableDictionary
>dictionaryWithObjectsAndKeys:@"aaa2",@"key1",@"bbb2",@"key2",@"ccc2",@"key3"
>,nil];
> NSMutableDictionary *dic3 = [NSMutableDictionary
>dictionaryWithObjectsAndKeys:@"aaa14",@"key1",@"bbb3",@"key2",@"ccc3",@"key3
>",nil];
> NSMutableDictionary *dic4 = [NSMutableDictionary
>dictionaryWithObjectsAndKeys:@"aaa15",@"key1",@"bbb4",@"key2",@"ccc4",@"key3
>",nil];
>
> [arr addObject: dic1 ];
> [arr addObject: dic2 ];
> [arr addObject: dic3 ];
> [arr addObject: dic4 ];
>
> NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:
>@"key1" ascending: YES selector: @selector( compareNumerically: )];
>
> NSLog([arr description]);
> NSLog([[arr sortedArrayUsingDescriptors:[NSArray
>arrayWithObject:descriptor]] description]);
>
>- (NSComparisonResult)compareNumerically:(NSString *)string
> {
> return [self compare:string options:(NSNumericSearch |
>NSCaseInsensitiveSearch)];
> }
>
>Peter
>
>Ursprungligt meddelande
>
>> See NSSortDescriptor initWithKey:ascending:selector:
>>
>> Normally NSSortDescriptor will just call compare: on both objects.
>> Using the method above you can tell it to call a different compare
>> method. So...
>>
>> sd = [[NSSortDescriptor alloc] initWithKey: @"name" ascending: YES
>> selector: @selector( compareNumerically: )];
>>
>> Will do what you want assuming you've implemented compareNumerically
>> for the objects in the array.
>>
>> Guy
_______________________________________________
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
References: | |
| >RE: Sorting (From: "Peter Karlsson" <email@hidden>) |