If you are concerned about performance and you want to check for a single character, using the -characterAtIndex: method might be faster. -hasSuffix: takes a string, so potentially more work needs to be done than just checking a single character (although the difference may be trivial).
You can also use categories to add a method to NSString as follows:
@interface NSString(StringUtilities) - (BOOL) endsWithCharacter: (unichar) c; @end @implementation NSString(StringUtilities) - (BOOL) endsWithCharacter: (unichar) c { NSUInteger length = [self length]; return (length > 0) && ([self characterAtIndex: length - 1] == c); } @end // test it... NSString *data = @"abcd,"; if ([data endsWithCharacter: L',']) { }
Of course you should comment, of course. Keep in mind that by adding endWithCharacter to the method, we added overhead to it that will distort the profiling results if you do not do the same when profiling alternatives.
All of this is probably a premature optimization for most cases - but, of course, if you do this test thousands of times per second, it can make a difference (in this case, you probably want to use the code directly in a loop, because the message passing inside is hard inner loop is not a great plan).
Sam Deane Jul 16 2018-10-10T00: 00-07
source share