Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if *number* is in a array

Pretty basic programming question, I know PHP have a function for it, but does the iPhone OS have one?

I want to check if the current indexPath is a value in an array.

PHP Example:

<?php
$indexPath = 3;
$array = array("0", "1", "2", "3", "4");
if (in_array($indexPath, $array)) {
  // Do something
}
?>

Does anybody know how to do the same thing in iOS?

like image 935
Emil Avatar asked Nov 27 '22 12:11

Emil


2 Answers

containsObject:
Returns a Boolean value that indicates whether a given object is present in the receiver.

- (BOOL)containsObject:(id)anObject

For example:

if ([arrayofNumbers containsObject:[NSNumber numberWithInt:516]])
    NSLog(@"WIN");

or to check an indexPath:

if ([arrayofIndexPaths containsObject:indexPath])
    NSLog(@"Yup, we have it");

I should clarify that an NSIndexPath is not a number but a series of numbers that "represents the path to a specific node in a tree of nested array collections" as explained in more detail in the developer documentation.

like image 50
prendio2 Avatar answered Dec 16 '22 03:12

prendio2


You want containsObject or indexOfObject:

unsigned int myIndex = [myArray indexOfObject: [NSNumber numberWithInt: 3]];
if(myIndex != NSNotFound) {
     // Do something with myIndex
}

Or:

if([myArray containsObject: [NSNumber numberWithInt: 3]]) {
    // Just need to know if it's there...
}
like image 38
Jeff B Avatar answered Dec 16 '22 05:12

Jeff B