1

I am trying to sort an array by the highest number that I assigned to each entry in the array.

However i don't think it's doing anything. Any suggestions on where the error may be?

Thanks!

 - (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];
}
6
  • what is "percentMatched" Commented Nov 17, 2012 at 0:47
  • it isnt... it calculates a percentage and assigns it to the entry. I am trying to filter from highest to lowest percentage. Commented Nov 17, 2012 at 0:51
  • also how would i only include entries that had a 20% or more? Commented Nov 17, 2012 at 1:01
  • There is nothing wrong with this method, it's doing the job.Probably the mistake you do is at calling it, or the key is not valid. Commented Nov 17, 2012 at 1:50
  • for filtering you can use NSPredicateFilter. Commented Nov 17, 2012 at 3:24

1 Answer 1

1

I'm intrigued by why your sort doesn't work. This does:

#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);
    }
}

Prints 10 20 100 to the console as expected.

Sign up to request clarification or add additional context in comments.

1 Comment

you were right... it works well, other methods were having the problem. It was surprisingly fast!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.