objc-obsessive
objc-obsessive

Reputation: 825

Quicker if statements

I am trying to create an iOS app which involves one main if statement to check if a text box contains certain text. I would like to check for multiple instances of a certain word but I don't want to do multiple if statements as this will dramatically slow down the performance of the app.

How can I check if a word matches that of a word in an NSArray, and if it does, return a NSString associated with that word in another text box?

Upvotes: 0

Views: 192

Answers (3)

trojanfoe
trojanfoe

Reputation: 122391

You can create an NSDictionary of the words you are checking against mapped against the NSString you want returned when that word is entered:

NSDictionary *words = [[NSDictionary alloc] initWithObjectsAndKeys:
    @"word1", @"result1",
    @"word2", @"result2",
    /*etc*/
    nil];

NSString *wordFromTextBox = ...;
NSString *result = [words objectForKey:keyword];
if (result != nil)
{
    // use result
}
else
{
    // word wasn't something we expected
}

// Some time later
[words release];

EDIT: To iterate over the list so you can test if the keywords are contained in the textbox, you can do the following (assume words and wordFromTextBox are set-up as before):

NSEnumerator *enumerator = [words keyEnumerator];
while ((NSString *keyword = [enumerator nextObject]) != nil)
{
    if ([wordFromTextBox rangeOfString:keyword].location != NSNotFound)
    {
        NSLog(@"The text box contains keyword '%@'", keyword);
        NSString *result = [words objectForKey:wordFromTextBox];
        // Use the result somehow
        break;
    }
}

Upvotes: 4

meronix
meronix

Reputation: 6176

for array, you can get an idea from this code:

NSArray* myArray = [[NSArray alloc] initWithObjects:@"one",@"two",@"three",@"four", nil];
NSString* stringToSearch = @"four";
NSUInteger indexPositionInArray = [myArray indexOfObject:stringToSearch];
NSLog(@"position in array: %i", indexPositionInArray);
if (indexPositionInArray !=  NSNotFound) {
    NSLog(@"String found in array: %@", [myArray objectAtIndex:indexPositionInArray]);
}

NSString* stringToSearch2 = @"fourrrr";
NSUInteger indexPositionInArray2 = [myArray indexOfObject:stringToSearch2];
NSLog(@"position in array: %i", indexPositionInArray2);
if (indexPositionInArray2 !=  NSNotFound) {
    NSLog(@"String found in array: %@", [myArray objectAtIndex:indexPositionInArray]);
}

Upvotes: 1

Aaron Hayman
Aaron Hayman

Reputation: 8502

I'd use a NSMutableDictionary/NSDictionary. The dictionary keys will be the words you're looking for. The values will be the words you wish to return. Once you've got the dictionary setup simply call [dict valueForKey:textbox.text]. The dict will return nil if the entry isn't in there, so you can test for that condition. All in all, I think this is probably the quickest way.

Upvotes: 1

Related Questions