views:

235

answers:

2

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 inthe iPhone OS?

+5  A: 

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...
}
Jeff B
+5  A: 

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.

prendio2
More specifically on the iPhone, you should look at the NSIndexPath UITableView category, which is where they define the concept of section and row... NSIndexPath itself is very abstract, but on the iPhone you really just end up using it for those two numbers.
Kendall Helmstetter Gelner
Thanks, but it's not working..I've got an array with the values 3, 8 and 2. I'm using this to check if the indexpath.row is there.`if ([array containsObject:[NSNumber numberWithInt:indexPath.row]]){ NSLog(@"WIN"); }`
Emil
can you show the code you used to construct your array? is it made up of NSNumbers or ints?
prendio2