Hi..
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
Hi..
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
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.
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
}
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
}
}
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.
containsObject:
on the NSArray
will do this for you. Simple and probably fastest for small array sizes.containsObject:
to check for existence