2012-11-17 95 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

你是對的...它工作得很好,其他方法都遇到的問題。這是驚人的快! –