Check if an NSString is just made out of spaces
Try stripping it of spaces and comparing it to @"":
NSString *probablyEmpty = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
BOOL wereOnlySpaces = [probablyEmpty isEqualToString:@""];
It's significantly faster to check for the range of non-whitespace characters instead of trimming the entire string.
NSCharacterSet *inverted = [[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet];
NSRange range = [string rangeOfCharacterFromSet:inverted];
BOOL empty = (range.location == NSNotFound);
Note that "filled" is probably the most common case with a mix of spaces and text.
testSpeedOfSearchFilled - 0.012 sec
testSpeedOfTrimFilled - 0.475 sec
testSpeedOfSearchEmpty - 1.794 sec
testSpeedOfTrimEmpty - 3.032 sec
Tests run on my iPhone 6+. Code here. Paste into any XCTestCase subclass.
NSString *str = @" ";
NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
if ([[str stringByTrimmingCharactersInSet: set] length] == 0)
{
// String contains only whitespace.
}
Try this:
[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
or
[mystring stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];