Life & Technology

Handful lessons in different areas of technology and life in general.

Monthly Archives: March 2012

NSString Category Function: isIn()

Usually when we’re trying to check if two strings are equal, we often used this code:

 NSString *isoView = @"Isometric View";
 if([isoView isEqualToString:@"Parallel View"]) // do something

Which is fine but if you’re testing against multiple values for equality, you might end up writing code like this:

 NSString *isoView = @"Isometric View";
 if([isoView isEqualToString:@"Parallel View"] || [isoView isEqualToString:@"Dynamic View"]
    || [isoView isEqualToString:@"Inverted View"] || [isoView isEqualToString:@"Range View"])
     // Do somethng here

And you’re code will contain bunch of ORs ( || ) just to test if your string matches to your qualifiers.

NSString+Additions
With this problem, I have created a simple NSString Category that basically solves this kind of situation and improves your code a little bit. I created a boolean function that accepts multiple string values terminated by nil that will be used for equality check of string.

Our interface header looks like this:

// NSString+Additions.h
#import <Foundation/Foundation.h>

@interface NSString (Additions)
- (BOOL) isIn: (NSString *) strings, ... NS_REQUIRES_NIL_TERMINATION;
@end

And the implementation code is a simple for .. loop to achieve our goal:

// NSString+Additions.m
#import "NSString+Additions.h"

@implementation NSString (Additions)

- (BOOL) isIn: (NSString *) strings, ...
{
    BOOL isFound = NO;

    va_list args;
    va_start(args, strings);
    for (NSString *arg = strings; arg != nil; arg = va_arg(args, NSString*))
    {
        if ([self caseInsensitiveCompare:arg] == NSOrderedSame) {
            isFound = YES;
            break;
        }
    }
    va_end(args);

    return isFound;
}
@end

If we’re going back to our sample snippets above, we would then write the conditional checking as follows:

NSString *isoView = @"Isometric View";
if ([isoView isIn:@"Parallel View", @"Dynamic View", @"Inverted View", @"Range View", nil])
   // Do Something

Simple and not cluttering with OR ( || ) statements!

The basic principle on the above Category is based on Objective C feature called Variable Argument Lists which is explained clearly by Matt on his blog post.

The category is easy to override to include checking against NSArray or NSDictionary.

Advertisements