Finding substrings in iOS

It one point I experimented with using titles on my answer buttons to keep track of which answer was selected. I switched to tags since they are integers and they are easier to use in this particular implementation. In any case, I though it interesting to show how to get a substring from a string. My titles are of the form, ‘Answer1’, ‘Answer2’, … ‘Answer16′. I really only need the last one or two digits. I pass an NSString into the delegate method from a button press.


- (void)checkBoxTapped:(UIButton *)buttonPressed {
    [[self delegate] quizAnswered:buttonPressed.currentTitle];
}

Then I grab either the last digit or the last two digits from the string.


NSString *answer = [selectedAnswer substringWithRange:NSMakeRange(6, 1)]; // wrongAnswer - wA
if (selectedAnswer.length == 8) wA = [selectedAnswer substringWithRange:NSMakeRange(6, 2)];

I was doing a string comparison to decide which question was answered,


if ([answer isEqualToString:@"1"] || 
    [answer isEqualToString:@"2"] || 
    [answer isEqualToString:@"3"] || 
    [answer isEqualToString:@"4"] ) {
    // do something
}

What I should have done is convert the string to an int and then do a simple comparison.


NSInteger answerAsInt = [answer intValue];
if ([answerAsInt < 5 ) {
    // do something
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.