0

I'm trying to sort through an array of objects to find the highest number. I'm fairly new with objective C (and C in general), so I am not sure why this isn't working, although my gut says its probably due to the NSNumber declaration. The max variable is always returned as random value from the array. Any ideas?

 NSNumber * max = 0;

    for (int i=0; i<mutableChartData.count; i++) {



     if ([mutableChartData objectAtIndex:i] > max) {
            max =[mutableChartData objectAtIndex:i];

        }


    }
spogebob92
  • 1,474
  • 4
  • 23
  • 32
  • Are you sure you want to use a pointer? – Biffen Sep 03 '14 at 11:39
  • check this [link](http://stackoverflow.com/questions/3080540/finding-maximum-numeric-value-in-nsarray) – Pawan Rai Sep 03 '14 at 11:40
  • 2
    The reason your code isn't working is that you're comparing the entries in the array incorrectly. Objective-C collection classes can only store objects e.g. NSObject descendants such as NSNumber - which it looks like you're using here. Object variables e.g. your max variable are pointers, not actual objects. Therefore, when you look at the value of max you wont see the actual NSNumber object, instead you see a memory reference - which points to the location of the NSNumber object. – mmccomb Sep 03 '14 at 11:58
  • A @mmccomb indicates, your `max` should be declared as `long` or `int` (or, perhaps, `NSInteger`) and you should do `[[mutableChartData objectAtIndex:i] longValue] > max` in your compare and assign the `longValue` to `max` if the compare is true. – Hot Licks Sep 03 '14 at 12:05
  • Thank you @HotLicks, I had been trying the "longValue" stuff, but didn't quite get the syntax right with the braces. – spogebob92 Sep 03 '14 at 12:17
  • But this is stuff you should know. In particular, the difference between a number and a pointer is critical, and you will get into deep trouble in Objective-C if you don't clearly "get" the difference. – Hot Licks Sep 03 '14 at 12:38
  • Hence why I'm posting here to learn... – spogebob92 Sep 03 '14 at 12:46
  • My point is that you should not attempt Objective-C programming unless you already have a good foundation in this stuff. – Hot Licks Sep 03 '14 at 16:03

1 Answers1

-1

enumerate array using code below:

NSNumber *max = 0;

[mutableChartData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *Stop)
 {
     if ([mutableChartData[i] intValue] > [max intValue]) {
        max =mutableChartData[i];
    }

 }];

enumerartion is fast and efficient and you will get maximum number in array

chaithraVeeresh
  • 258
  • 3
  • 11