-1

I need to get the minimum value (and its index) among objects inside an NSMutable double array.

I get the minimum value correctly but I cannot get its index. A weird and very high number comes up. How can I retrieve the index?

double lowestvalue = 1.0;
double highestvalue = 100.0;
double n4 = 4.0;
double n2 = 2.0;
double n3 = 3.0;
double n1 = 10.0;

NSMutableArray *arr1 = [[NSMutableArray alloc] init];

NSNumber *num1 = [NSNumber numberWithDouble:n1];
NSNumber *num2 = [NSNumber numberWithDouble:n2];
NSNumber *num3 = [NSNumber numberWithDouble:n3];
NSNumber *num4 = [NSNumber numberWithDouble:n4];
NSNumber *numL = [NSNumber numberWithDouble:lowestvalue];
NSNumber *numH = [NSNumber numberWithDouble:highestvalue];

[arr1 addObject:num2];
[arr1 addObject:num3];
[arr1 addObject:num4];
[arr1 addObject:numL];
[arr1 addObject:num1];
[arr1 addObject:numH];

NSLog(@"arr1: %@",arr1);

NSNumber * min_ = [arr1 valueForKeyPath:@"@min.doubleValue"];
NSString *str1_ =[NSString stringWithFormat:@"%@",min_];
NSInteger path1_ =[arr1 indexOfObject:str1_];
NSIndexPath *indepath1_ =[NSIndexPath indexPathForItem:path1_ inSection:0];

NSLog(@"Min_ Value = %f and index_ = %ld",[min_ doubleValue], (long)indepath1_.row);


//Min_ Value = 1.000000 and index_ = 9223372036854775807

1 Answer 1

0

Your "weird" number is NSNotFound, which you will find is covered in the documentation under the "Return Value" section.

The reason your object is not found is you have an array of NSNumber * references/objects, valueForKeyPath returns an NSNumber * which you store in min_, you then produce a different NSString object (effectively creating a "picture" of your NSNumber object) storing its reference in str1, and then ask indexOfObject if your new object of a different type is in your array – answer NSNotFound.

HTH

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

6 Comments

Got it. Many thanks for pointing it out. However how can I get the index of the minimum number?
@jeddi - lookup the object from the array, e.g. [arr1 indexOfObject:min_]
It gives me exactly the same issue (NSNotFound)
By the way, this is not the problem. My code works perfectly fine if the array is composed of strings, but it fails to return the index when the doubles are wrapped in NSNumbers. There must be a problem here: NSNumber *num1 = [NSNumber numberWithDouble:n1];
Or the problem is the formatting of the NSLog...... NSLog(@"Min_ Value = %f and index_ = %ld",[min_ doubleValue], (long)indepath1_.row); Any idea?
|

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.