1

我正在尝试按分配给数组中每个条目的最高编号对数组进行排序。

但是我不认为它在做任何事情。关于错误可能在哪里的任何建议?

谢谢!

 - (NSArray*)sortByPercentage:(NSArray*)array {

    NSArray *inputArray = array;
    NSSortDescriptor *sortDescriptor = [[ NSSortDescriptor alloc] initWithKey:@"percentMatched" ascending:YES];

    //nov 8
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    NSArray *finalResult = [inputArray sortedArrayUsingDescriptors:sortDescriptors];
    [sortDescriptor release];
    return [NSArray arrayWithArray:finalResult];
}
4

1 回答 1

1

我对为什么你的排序不起作用很感兴趣。这样做:

#import <Foundation/Foundation.h>

@interface FooObject : NSObject
@property (nonatomic, assign) NSInteger value;
@property (readonly) NSInteger percentMatched;
@end

@implementation FooObject
@synthesize value;

//  compute percentMatched as an elementary function of value
- (NSInteger)percentMatched {
    return value * 2;
}
@end

int main(int argc, char *argv[]) {
    NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];

    FooObject *foo1 = [[FooObject alloc] init];
    foo1.value = 50;

    FooObject *foo2 = [[FooObject alloc] init];
    foo2.value = 5;

    FooObject *foo3 = [[FooObject alloc] init];
    foo3.value = 10;

    NSArray *myFoos = [NSArray arrayWithObjects:foo1,foo2,foo3,nil];
    NSArray *sorters = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"percentMatched" ascending:YES]];
    NSArray *mySortedFoos = [myFoos sortedArrayUsingDescriptors:sorters];
    for(FooObject *foo in mySortedFoos ) {
        printf("%ld ",foo.percentMatched);
    }
}

按预期打印10 20 100到控制台。

于 2012-11-17T11:20:58.267 回答