2012-11-17 62 views
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]; 
} 
+0

什么是“percentMatched” – MCKapur

+0

它不是......它计算的百分比,并将其分配到的条目。我正在尝试从最高百分比过滤到最低百分比。 –

+0

也我怎么会只包括有20%或更多的条目? –

回答

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到预期的控制台。

+0

你是对的...它工作得很好,其他方法都遇到的问题。这是惊人的快! –