Compare an int to an array of ints Obj-C
How do i go about seeing if my integer is in an array of integers...
开发者_如何学运维eg i want to know if 7 is in an array of [ 1 3 4 5 6 7 8]
any ideas?
Thanks
There are several ways to do this depending on factors such as size of the array - how often you need to search, how often you need to add to the array etc. In general this is a computer science problem.
More specifically I'd guess there are three options likely to best fit your needs.
- "Brute force": just loop through the array looking for the value. Calling
containsObject:
on theNSArray
will do this for you. Simple and probably fastest for small array sizes. - Copy the array into a set and use
containsObject:
to check for existence - Keep the values in the array, but sort the array and implement your own binary search - which is probably not as complex as it sounds.
This depends on the type of array you have, if it's an object or a C array. Judging by your tags you've got an NSArray with NSIntegers, this would be wrong. NSIntegers are not objects and cannot be put into an NSArray, unless you wrap them into an object, for example an NSNumber.
NSArray
Use the containsObject:
method.
I'm not entirely sure how you put your integers into an NSArray. The usual way to do this is to use NSNumber.
NSArray *theArray = [NSArray arrayWithObjects:[NSNumber numberWithInteger:1],
[NSNumber numberWithInteger:7],
[NSNumber numberWithInteger:3],
nil];
NSNumber *theNumber = [NSNumber numberWithInteger:12];
/*
* if you've got the plain NSInteger you can wrap it
* into an object like this:
* NSInteger theInt = 12;
* NSNumber *theNumber = [NSNumber numberWithInteger:theInt];
*/
if ([theArray containsObject:theNumber]) {
// do something
}
C-Array
I suspect you're using a C-Array. In that case you have to write your own loop.
NSInteger theArray[3] = {1,7,3}
NSInteger theNumber = 12;
for (int i; i < 3; i++) {
if (theArray[i] == theNumber) {
// do something
break; // don't do it twice
// if the number is twice in it
}
}
//assume these data, either from a method call or instance variables
int theArray[7] = {1,7,3,8,5,7,4};
int numberIWant = 8;
//this is the essence in a C-array, which you can easily use on ios
BOOL isNumberFound = NO;
for (int i; i < sizeof(theArray)/sizeof(int); i++) {
if (theArray[i] == numberIWant) {
isNumberFound = YES;
break; //breaks the for loop
}
}
//return the bool, or otherwise check the bool
if (isNumberFound)
{
//do stuff
}
精彩评论