Reputation: 13
I have an array with double values that can range from 0.0 to 100.0. I would like to alert the user if any of the values are below 10.0. I did some searching and the closest thing I could find was:
- (BOOL)containsObject:(id)anObject
Is there any way I could use this method to see if the values are below 10? I tried the following line of code but received two errors.
if ([myArray containsObject:[NSNumber numberWithDouble:(<10)])
{
// Do something
}
I would appreciate the assistance. It seems like a pretty basic task.
Upvotes: 0
Views: 117
Reputation: 3918
If it is not an array with lots of data, I don't see the reason why wouldn't you do it like this:
for (NSNumber *number in myArray) {
if ([number floatValue] < 10.0) {
// alert user
}
}
Upvotes: 5
Reputation: 15566
I would use blocks, they are cooler and it will help to familiarize yourself with them:
[myArray enumerateObjectsWithBlock^(NSNumber *number, NSUInteger indx, BOOL *stop) {
if ([number floatValue] < 10.0) {
// alert user
// kill the loop to prevent unnecessarily going through all the elements
stop = YES;
}
}];
If you do want to user fast enumeration include a break:
for (NSNumber *number in myArray) {
if ([number floatValue] < 10.0)
// alert user
break; // kills the loop
}
}
If you only care if one item is under 10 these approaches work well because you do not need to go through every element every time. Also, if this is the case, predicates are not efficient because they will filter the whole array when in reality you only care about one item (the first item under 10).
Upvotes: 0
Reputation: 47049
Use NSPredicate
for more faster
NSPredicate *predicatePeople = [NSPredicate predicateWithFormat:@"(startValue => %f) BETWEEN (endValue <= %f))",startNSNumber,endNSNumber];
NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicatePeople];
if(filteredArray.count > 0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Information" message:@"MyArray Contain between 1 to 10 value" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
}
Upvotes: 1
Reputation: 269
Also, the usage of containsObject:
is for "equals" purpose, like [myArray containsObject:[NSNumber numberWithDouble:2.0]]
, not conditional like you did.
So, the best is what JPetric mentioned.
for (NSNumber *number in myArray) {
if ([number floatValue] < 10.0) {
// alert user
}
}
Upvotes: 0