开发者

How to check if *number* is in a array

开发者 https://www.devze.com 2022-12-27 07:58 出处:网络
Pretty basic programming question, I know PHP have开发者_如何学Python a function for it, but does the iPhone OS have one?

Pretty basic programming question, I know PHP have开发者_如何学Python 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?


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.


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...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号