An Objective-C category to determine true/false status of arbitrary strings

NOTE: This one’s for the coders (or coders-to-be) in the audience. If you’re not looking for source code or technical information, anorexia you might want to skip to the next/previous post.

As anyone who deals with program logic knows, buy viagra most decisions come down to a choice between one of two options: true or false.

Unfortunately, prescription when reading data back from remote or unknown sources (or, god forbid, receiving text from a mere human typing on its keyboard), one often finds it necessary to jump through a series of hoops to figure out whether the actual response means yes or no.

As humans, we understand that “ok,” “sure,” “yep,” and “correct” all generally mean the same thing (“true”), and likewise, “nope,” “unh-uh,” “not a chance,” and “are you kidding me?” usually mean the opposite (“false”). You could test for all of these possibilities each time (I have in the past), or write a function that loops through the myriad of choices when they arise (I’ve done that too), or you could just use a simple Objective-C category like the one presented below to let the response itself tell you what it means.

One of my favorite features of the Objective-C programming language is the availability of class extensions, or categories. Unlike subclasses or external utility libraries, categories allow us to bend the language itself to our will — adding or overriding the default behavior of built-in Cocoa classes to make them behave as we need.

If you’re not clear on how to use categories to your advantage, I’d highly suggest learning more about them, perhaps starting with Item #11 of Cocoa Dev Central’s excellent introduction to Objective-C (You remember, that single-page tutorial you visited when you first installed that new copy of Xcode way back when).

The code presented here is nothing fancy, and it could no doubt be made more efficient, but I tend to keep it this way, as it’s easy to read, and more importantly, it’s easy to add/subtract new words that mean “yes” to it. You can always go back and add fancier string-parsing functions later, but I tend to reach for this snippet when I need to do a lot of true/false parsing quickly.

Feel free to use this category in your own work, or adapt it to your own needs. Basically, it translates a string such as “OK” or “sure” into the boolean value, true, and other, unknown phrases into false.

Its use is as follows:

[code language="objc"]
#import "NSString+BooleanLogic"
.
.
.
NSString *stringToTest = @"ok";
if ([stringToTest evaluatesTo: YES]) { // Does 'ok' mean yes?
NSLog (@"The phrase %@ evaluates to true!", stringToTest); // Yep!
}

// Check if an http response code string indicates a success...
// In http-speak, 200 indicates success, so a 500 (server error) would evaluate as 'NO'
//
NSString *httpResponseCode = "500"; // HTTP response code 500 indicates a server error
if ([httpResponseCode evaluatesTo: NO]) {
NSLog (@"The server responded with an error.");
}
[/code]
The NSString+BooleanLogic source follows:

NSString+BooleanLogic header

[code language="objc"]
/*

NSString+BooleanLogic.m

Created by Mike Fahy on 9/7/11.
Copyright (C) 2011 Phacia Inc.

http://www.phacia.com/?p=1341

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

@interface NSString (NSString_BooleanLogic)

/*
Common strings that generally mean "yes" can now be evaluated as "true"

ie:

NSString *stringToTest = @"ok";

if ([stringToTest evaluatesTo: YES]) {
NSLog (@"The phrase %@ evaluates to true!", stringToTest);
}

*/

-(BOOL) evaluatesTo: (BOOL) b;

@end

[/code]
NSString+BooleanLogic implementation
[code language="objc"]
/*

NSString+BooleanLogic.m

Created by Mike Fahy on 9/7/11.
Copyright (C) 2011 Phacia Inc.

http://www.phacia.com/?p=1341

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#import "NSString+BooleanLogic.h"

@implementation NSString (NSString_BooleanLogic)

-(BOOL) evaluatesTo: (BOOL) b
{
// Feel free to add your own "true" sayings inside this array to ensure they evaluate to true.

NSArray *positive = [NSArray arrayWithObjects:
@"yes",
@"true",
@"ok",
@"okay",
@"right",
@"correct",
@"success",
@"positive",
@"absolutely",
@"sure",
@"yep",
@"good",
@"gotcha",
@"affirmative",
@"200",
@"10-4",
@"roger",
@"check",
@"will do",
@"1",
nil
];

return (b) ? [positive containsObject: [self lowercaseString]]
: (![positive containsObject: [self lowercaseString]])
;
}

@end

[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>