Skip to content

Instantly share code, notes, and snippets.

@evgeniyd
Last active August 29, 2015 14:26
Show Gist options
  • Save evgeniyd/76ddbafa6d3e96cc2bb9 to your computer and use it in GitHub Desktop.
Save evgeniyd/76ddbafa6d3e96cc2bb9 to your computer and use it in GitHub Desktop.
The behaviour of rangeOfString: you might probably not aware about
#import <Foundation/Foundation.h>
@interface MyStringUtils : NSObject
+ (BOOL)confuzion_stringContainsVotedKeywords:(NSString*)input;
+ (BOOL)stringContainsVotedKeywords:(NSString*)input;
@end
#import "MyStringUtils.h"
@implementation MyStringUtils
+ (BOOL)confuzion_stringContainsVotedKeywords:(NSString*)input
{
NSRange votedRange = [input rangeOfString:@"voted"];
if (votedRange.location != NSNotFound) {
return YES;
}
else {
return NO;
}
}
+ (BOOL)stringContainsVotedKeywords:(NSString*)input
{
if (input) {
NSRange votedRange = [input rangeOfString:@"voted"];
if (votedRange.location != NSNotFound) {
return YES;
}
}
return NO;
}
@end
@interface SightingStringUtilsTests : XCTestCase
@end
@implementation SightingStringUtilsTests
- (void)setUp {
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown {
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
- (void)testStringContainsVotedKeywords
{
NSString* testString = nil;
XCTAssertFalse([SightingStringUtils stringContainsVotedKeywords:testString]); // test passed
XCTAssertFalse([SightingStringUtils confuzion_stringContainsVotedKeywords:testString]); // test FAILED
// the reason it is failed, b/c [nil rangeOfString:@"some string"] returns location == 0, which is not the same as location == NSNotFound
// below this line: tests passed no matter which variant of method you would choose
testString = @"";
XCTAssertFalse([SightingStringUtils stringContainsVotedKeywords:testString]);
testString = @"voted";
XCTAssertTrue([SightingStringUtils stringContainsVotedKeywords:testString]);
testString = @"blah-blah voted blah-blah";
XCTAssertTrue([SightingStringUtils stringContainsVotedKeywords:testString]);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment