4

I have an array of strings.

How might I be able to figure out what index a string is in a array?

2 Answers 2

10

-[NSArray indexOfObject:]

Sign up to request clarification or add additional context in comments.

6 Comments

wow? That was... Simple. Hahah I'll give it a try and get back to you.
This is only going to work if you have a reference to the same string object that was put in the array. Not just a string that has the same value.
It will work when using indexOfObject:@"Some string"! indexOfObject: uses isEqual: on the objects in the array, and NSString's implementation of isEqual: tests the value of the string, not the pointer ;)
I'm getting an error about the index being out of range when I try to use the value returned from indexOfObject: It says that the returned index is something crasy like 201341023 or something... My array is literally 3 things long.
That number is actually NSNotFound, which is returned when the object was not found in the array.
|
1

Though very old but this question comes quite high in google search. Here is a version in using block,

- (void)testSearch
{
    NSArray *hashAlgorithms = @[@"SHA1", @"SHA2", @"SHA256", @"SHA384", @"SHA512"];
    NSString *searchFor = @"SHA384";
    __block NSInteger index = NSNotFound;
    [hashAlgorithms enumerateObjectsUsingBlock:^(id alg, NSUInteger idx, BOOL *stop) {
        if ([alg compare:searchFor options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            NSLog(@"Found: %@", searchFor);
            *stop = YES;
            index = idx;
        } else {
            NSLog(@"NOT Equal: %@", alg);
        }
    }];

    if (index == NSNotFound) {
        NSLog(@"Not found. %li", (long)index);
    } else {
        NSLog(@"Found at: %li", (long)index);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.