views:

188

answers:

2

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

+1  A: 

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
    }
}
Georg
Judging by the tags he used it looks like he's using NSIntegers in an NSArray
Phil Nash
@Phil Nash: That's what I thought too, but using plain NSIntegers in an NSArray isn't possible. NSInteger isn't an object, it's just a typecasted int or long.
Georg
you are right of course :-) I really hate having to do boxing and unboxing in Objective-C. Good job we can use Monotouch instead. Oh wait...
Phil Nash
+3  A: 

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.

  1. "Brute force": just loop through the array looking for the value. Calling containsObject: on the NSArray will do this for you. Simple and probably fastest for small array sizes.
  2. Copy the array into a set and use containsObject: to check for existence
  3. 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.
Phil Nash
No.1 did the trick.. the array had about 16 items. Cheers Phil
Sam Jarman