首先尝试排序数组

时间:2012-11-17 00:45:45

标签: objective-c ios xcode nsarray

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

然而,我不认为它在做任何事情。 有关错误可能位置的任何建议吗?

谢谢!

 - (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];
}

1 个答案:

答案 0 :(得分: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打印到控制台。