0

I am receiving an array of object in the function below, each item in that array contains a value, which is type of CGFloat, I am using this function below, but getting an error at the return line : "Expected identifier"

- (void)setupPieChartWithItems:(NSArray *)items {

    NSArray *sortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        CGFloat first = [(PNPieChartDataItem*)a value];
        CGFloat second = [(PNPieChartDataItem*)b value];
        return [first > second];
    }];
}

Where is the error? Any idea?

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
  • https://stackoverflow.com/questions/50286901/sorting-an-array-of-object-with-respect-to-the-float-value ? `[first > second]` first is like asking a method named `>` on two objects `first` and `second` but they aren't objects, they are primitive. – Larme May 11 '18 at 12:16

3 Answers3

0

Issue may be with the brackets in this [first > second]; as sortedArrayUsingComparator is required to return NSComparisonResult value not array of bool value

replace your code with

- (void)setupPieChartWithItems:(NSArray *)items {

    NSArray *sortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        CGFloat first = [(PNPieChartDataItem*)a value];
        CGFloat second = [(PNPieChartDataItem*)b value];
        return [[NSNumber numberWithFloat:first] compare:[NSNumber numberWithFloat:second]];

     }];
}

Hope it is helpful

Prashant Tukadiya
  • 15,838
  • 4
  • 62
  • 98
0

You can replace your code for sorting with this one :

NSSortDescriptor *highestToLowest = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES];
NSMutableArray *sortedArray = items.mutableCopy;
[sortedArray sortUsingDescriptors:[NSArray arrayWithObject:highestToLowest]];

Setting YES to ascending will result in 1.3, 2.6, 3.1… whereas setting NO will result in 3.1, 2.6, 1.3…

Tell me if you need any help :)

AnthoPak
  • 4,191
  • 3
  • 23
  • 41
0

Remove the brackets from [first > second] to fix the compiler error, and the block must return a NSComparisonResult:

- (void)setupPieChartWithItems:(NSArray *)items {
    NSArray *sortedArray = [items sortedArrayUsingComparator:^NSComparisonResult(PNPieChartDataItem *a, PNPieChartDataItem *b) {
        CGFloat first = [a value];
        CGFloat second = [b value];
        if (first > second)
            return NSOrderedDescending;
        if (first < second)
            return NSOrderedAscending;
        return NSOrderedSame;
    }];
}

Like in this answer how to sort an NSArray of float values?.

Willeke
  • 14,578
  • 4
  • 19
  • 47