How do I test if an NSString
is empty in Objective-C?

- 37,241
- 25
- 195
- 267

- 18,135
- 25
- 89
- 129
31 Answers
You can check if [string length] == 0
. This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length
on nil will also return 0.

- 113,588
- 46
- 195
- 237

- 40,399
- 3
- 75
- 82
-
14There are some very rare NSStrings where this will result in a false negative (saying the string isn't empty, when, for practical purposes, it is). Consider `@"\u200B"` (consisting only of Unicode character [ZERO WIDTH SPACE](http://www.fileformat.info/info/unicode/char/200B/index.htm). Printing it out will print 0 characters (verify using monospaced font), but string.length will give 1. There are other Unicode characters (like [OBJECT REPLACEMENT CHARACTER](http://www.fileformat.info/info/unicode/char/fffc/encoding.htm)) which behave likewise. You may get the latter when parsing PDF text. – fzwo Jan 08 '14 at 14:12
-
52@fzwo not to be an arse, but in theory it doesn't give a false negative. It behaves **exactly** as you'd expect. Your interpretation of what `ZERO WIDTH SPACE` is doesn't really matter, because `@"\u200B"` **is** a character nonetheless so if you test for the string to be empty, it will say it isn't because there is a character in it. It's just not printable following the Unicode standard. – bmeulmeester Jun 18 '14 at 10:40
-
4Of course it is technically correct, I'm not debating that. I just want to caution that this may not exhibit the intended or expected behavior, which is why I wrote "for practical purposes". It depends on the intended meaning of "empty". – fzwo Jun 18 '14 at 12:51
-
5It's not a false negative. A "zero worth space" is a unicode character like any other. It's just "worth remembering" if relevant to your app. (Great thinking, fzwo!) – Fattie Jun 22 '14 at 19:09
-
I have a string that looks to be set to "". When I call the length method it returns nil not zero. So this check is failing for me in iOS 7. – lostintranslation Jul 16 '14 at 21:55
-
1@lostintranslation nil and zero are the same value. This approach _is_ still applicable in iOS7. – CrimsonChris Jul 18 '14 at 17:06
-
2Let me know if I'm wrong, but I think you could also omit == 0 part and add a negation in front: ``![string length]``. Seems more clean. – damirstuhec Aug 31 '14 at 20:29
-
3@damirstuhec That may be less characters, but it is also less readable. `if ([string length] == 0)` would be read as "if string length is zero", while `if (![string length])` would be read as "if not string length". If someone who is unfamiliar with that code reads it, the second choice would take longer to understand. – Brian Apr 20 '15 at 21:48
-
2@Brian I agree! 8 months later I actually like ``if (string.length == 0)`` the most. – damirstuhec Apr 21 '15 at 09:11
-
2This will fail if the string is NULL as you cannot call length on NULL. – Nov 14 '15 at 18:57
-
This doesn't work if the string is NSNull *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull length]: unrecognized selector sent to instance 0x10c252f28' – mike nelson Oct 27 '19 at 03:08
Marc's answer is correct. But I'll take this opportunity to include a pointer to Wil Shipley's generalized isEmpty
, which he shared on his blog:
static inline BOOL IsEmpty(id thing) {
return thing == nil
|| ([thing respondsToSelector:@selector(length)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [(NSArray *)thing count] == 0);
}
-
26If you want this to be very generalized, one could implement this logic as a category on NSObject instead of using a static method as shown here. – Brad The App Guy May 24 '09 at 00:59
-
17
-
14If you are in a situation where you don't know what type of object you are checking, I guess this works. However I suggest that if you don't know whether an object is NSData or NSArray, you have bigger problems. What's your next macro going to be after this call, condenseToSingleNSData(id thing)? expandToNSArray(id thing)? Sooner or later, you will be asking what kind of class you're dealing with, better to do it on first reference. – Brane Dec 10 '12 at 14:21
-
@Brane Good point, but not the point of the generalized function. The generality makes it possible to have a single function for use no matter what class `thing` is--that is, when you know what class it is already, but don't want to bother with creating a separate function for it. – JohnK Jun 25 '13 at 21:18
-
-
1@BradSmith, one could create a category for it but nil values would not be counted since the method would not be called. For instance, if thing = nil, [thing IsEmpty] would not be called and would always return false/NO. To check for nil, there needs to be a parameter. Nil objects cannot compare themselves as nil via a category. – Chris Dec 05 '13 at 13:03
-
3
The first approach is valid, but doesn't work if your string has blank spaces (@" "
). So you must clear this white spaces before testing it.
This code clear all the blank spaces on both sides of the string:
[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];
One good idea is create one macro, so you don't have to type this monster line:
#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]
Now you can use:
NSString *emptyString = @" ";
if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");

- 38,547
- 26
- 130
- 141

- 1,605
- 12
- 9
-
3Why use macros when they are not necessary? In this case any sort type safety is sacrificed for no real benefit. – E.M. Jul 22 '10 at 19:17
-
Is for simple convenience, if you like to write "[object stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]" everytime you want to check if one string is empty, is up to you. – SEQOY Development Team Jul 28 '10 at 23:44
-
18that would better be served by an `NSString` category that adds a method called `trimmedString` that does exactly what you wrote. – Dave DeLong Sep 11 '10 at 15:23
-
2Note that Apple's `whitespaceCharacterSet` does not include newlines! Here's a category I wrote including `trim` and some other useful methods: https://github.com/alexch/unsuck/blob/master/unsuck/NSString%2BUnsuck.m https://github.com/alexch/unsuck/blob/master/unsuckTests/NSString%2BUnsuckTests.m – AlexChaffee May 20 '13 at 01:38
-
@E.M. I'm not a fan of macros, but i don't understand your type-safety concern. During compilation the macro is replaced with its contents so if you invoke the macro with something different from a NSString you still get a message from the compiler. Categories would be far better anyway. – Zmaster Aug 08 '13 at 12:06
One of the best solution I ever seen (better than Matt G's one) is this improved inline function I picked up on some Git Hub repo (Wil Shipley's one, but I can't find the link) :
// Check if the "thing" passed is empty
static inline BOOL isEmpty(id thing) {
return thing == nil
|| [thing isKindOfClass:[NSNull class]]
|| ([thing respondsToSelector:@selector(length)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [(NSArray *)thing count] == 0);
}

- 21,218
- 14
- 66
- 75

- 2,766
- 5
- 32
- 39
-
2This is Wil Shipley's work. FYI, you can change [thing isKindOfClass:[NSNull class]] to just (thing == [NSNull null]) – Steve N Mar 07 '11 at 22:09
-
Phew.... exactly what I was looking for. I was going mad, trying to work out why my "cellForRowAtIndexPath" function was crashing due to null strings (and I couldn't catch the problem). This function solved it perfectly. – Mike Gledhill Feb 15 '12 at 12:01
-
Copy of @Brane comment: _If you are in a situation where you don't know what type of object you are checking, I guess this works. However I suggest that if you don't know whether an object is NSData or NSArray, you have bigger problems. What's your next macro going to be after this call, `condenseToSingleNSData(id thing)`? `expandToNSArray(id thing)`? Sooner or later, you will be asking what kind of class you're dealing with, better to do it on first reference._ – Cœur Mar 12 '18 at 05:24
You should better use this category:
@implementation NSString (Empty)
- (BOOL) isWhitespace{
return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
}
@end

- 37,241
- 25
- 195
- 267
-
6That definition would conlude that the string " /r/n /r/n" is empty, when it clearly is not - it contains whitespace. Your function is really: -(BOOL)isWhitespace(NSString*); – JBRWilkinson Mar 28 '10 at 20:52
-
6A corollary to this. I implemented this category, and there is a twist. If you call this on a nil string, this function is never called, and you get back a NO(or what evaluates to NO) as a return value. Then you think it's not empty...This might work if the name was isFilled or something like that. – Ying Oct 29 '10 at 13:53
-
I guess the right category would then be: `@implementation NSString (Empty) - (BOOL) empty{ return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]length] == 0); } @end` As a combination of Marc's and Kyle's answer. – palme Sep 25 '13 at 12:00
Another option is to check if it is equal to @""
with isEqualToString:
like so:
if ([myString isEqualToString:@""]) {
NSLog(@"myString IS empty!");
} else {
NSLog(@"myString IS NOT empty, it is: %@", myString);
}

- 51,908
- 16
- 134
- 170
I put this:
@implementation NSObject (AdditionalMethod)
-(BOOL) isNotEmpty
{
return !(self == nil
|| [self isKindOfClass:[NSNull class]]
|| ([self respondsToSelector:@selector(length)]
&& [(NSData *)self length] == 0)
|| ([self respondsToSelector:@selector(count)]
&& [(NSArray *)self count] == 0));
};
@end
The problem is that if self is nil, this function is never called. It'll return false, which is desired.

- 32,206
- 53
- 172
- 282
-
best solution since a) is instance method and b) category c) nil case on itself is handle by 'isNotEmpty' Thx! – Denis May 01 '14 at 19:38
-
Great idea, just too bad `-(BOOL)isEmpty{ return ![self isNotEmpty]}` won't work on category. – Alston Jun 15 '15 at 10:00
-
Copy of @Brane comment: _If you are in a situation where you don't know what type of object you are checking, I guess this works. However I suggest that if you don't know whether an object is NSData or NSArray, you have bigger problems. What's your next macro going to be after this call, `condenseToSingleNSData(id thing)`? `expandToNSArray(id thing)`? Sooner or later, you will be asking what kind of class you're dealing with, better to do it on first reference._ – Cœur Mar 12 '18 at 05:24
Just pass your string to following method:
+(BOOL)isEmpty:(NSString *)str
{
if(str.length==0 || [str isKindOfClass:[NSNull class]] || [str isEqualToString:@""]||[str isEqualToString:NULL]||[str isEqualToString:@"(null)"]||str==nil || [str isEqualToString:@"<null>"]){
return YES;
}
return NO;
}

- 305
- 2
- 9
-
Check out the comments on http://stackoverflow.com/questions/21605075/iphone-string-comparison-strange-issue-in-ios-6/21605308#21605308 to why this is wrong. Also how is this better then the other answers on here. – Popeye Feb 07 '14 at 12:58
May be this answer is the duplicate of already given answers, but i did few modification and changes in the order of checking the conditions. Please refer the below code:
+(BOOL)isStringEmpty:(NSString *)str {
if(str == nil || [str isKindOfClass:[NSNull class]] || str.length==0) {
return YES;
}
return NO;
}

- 1,550
- 2
- 21
- 33
-
This is a category, you can see how to create it here: http://goo.gl/bRcfn7. I like the idea of a category for this – Daniel Gomez Rico Jul 05 '14 at 22:40
-
No, we can not say this is category. If this function is implemented under the category of NSString class, then it is category. Otherwise we can call this method with the name of class wherever we implemented it. Like Bool isEmptyStr = [MyClassName isStringEmpty:str] But still, It will be more good if we will declare it under category. Because somehow we need to take the advantage of categories also. – iDevAmit Jul 07 '14 at 03:51
Swift Version
Even though this is an Objective C question, I needed to use NSString
in Swift so I will also include an answer here.
let myNSString: NSString = ""
if myNSString.length == 0 {
print("String is empty.")
}
Or if NSString
is an Optional:
var myOptionalNSString: NSString? = nil
if myOptionalNSString == nil || myOptionalNSString!.length == 0 {
print("String is empty.")
}
// or alternatively...
if let myString = myOptionalNSString {
if myString.length != 0 {
print("String is not empty.")
}
}
The normal Swift String
version is
let myString: String = ""
if myString.isEmpty {
print("String is empty.")
}
See also: Check empty string in Swift?
Simply Check your string length
if (!yourString.length)
{
//your code
}
a message to NIL will return nil or 0, so no need to test for nil :).
Happy coding ...

- 5,525
- 1
- 40
- 34
-
I have used this so many times. Absolutely no need for extensions, categories and what not. – pnizzle Jul 12 '18 at 03:22
Just use one of the if
else
conditions as shown below:
Method 1:
if ([yourString isEqualToString:@""]) {
// yourString is empty.
} else {
// yourString has some text on it.
}
Method 2:
if ([yourString length] == 0) {
// Empty yourString
} else {
// yourString is not empty
}

- 9,829
- 9
- 59
- 87

- 1,027
- 11
- 14
You can check either your string is empty or not my using this method:
+(BOOL) isEmptyString : (NSString *)string
{
if([string length] == 0 || [string isKindOfClass:[NSNull class]] ||
[string isEqualToString:@""]||[string isEqualToString:NULL] ||
string == nil)
{
return YES; //IF String Is An Empty String
}
return NO;
}
Best practice is to make a shared class say UtilityClass and ad this method so that you would be able to use this method by just calling it through out your application.

- 350
- 2
- 5
You have 2 methods to check whether the string is empty or not:
Let's suppose your string name is NSString *strIsEmpty
.
Method 1:
if(strIsEmpty.length==0)
{
//String is empty
}
else
{
//String is not empty
}
Method 2:
if([strIsEmpty isEqualToString:@""])
{
//String is empty
}
else
{
//String is not empty
}
Choose any of the above method and get to know whether string is empty or not.
Very useful post, to add NSDictionary support as well one small change
static inline BOOL isEmpty(id thing) {
return thing == nil
|| [thing isKindOfClass:[NSNull class]]
|| ([thing respondsToSelector:@selector(length)]
&& ![thing respondsToSelector:@selector(count)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [thing count] == 0);
}
-
Copy of @Brane comment: _If you are in a situation where you don't know what type of object you are checking, I guess this works. However I suggest that if you don't know whether an object is NSData or NSDictionary, you have bigger problems. What's your next macro going to be after this call, `condenseToSingleNSData(id thing)`? `expandToNSArray(id thing)`? Sooner or later, you will be asking what kind of class you're dealing with, better to do it on first reference._ – Cœur Mar 12 '18 at 05:25
It is working as charm for me
If the NSString
is s
if ([s isKindOfClass:[NSNull class]] || s == nil || [s isEqualToString:@""]) {
NSLog(@"s is empty");
} else {
NSLog(@"s containing %@", s);
}

- 14,325
- 6
- 82
- 89
So aside from the basic concept of checking for a string length less than 1, it is important to consider context deeply. Languages human or computer or otherwise might have different definitions of empty strings and within those same languages, additional context may further change the meaning.
Let's say empty string means "a string which does not contain any characters significant in the current context".
This could mean visually, as in color and background color are same in an attributed string. Effectively empty.
This could mean empty of meaningful characters. All dots or all dashes or all underscores might be considered empty. Further, empty of meaningful significant characters could mean a string that has no characters the reader understands. They could be characters in a language or characterSet defined as meaningless to the reader. We could define it a little differently to say the string forms no known words in a given language.
We could say empty is a function of the percentage of negative space in the glyphs rendered.
Even a sequence of non printable characters with no general visual representation is not truly empty. Control characters come to mind. Especially the low ASCII range (I'm surprised nobody mentioned those as they hose lots of systems and are not whitespace as they normally have no glyphs and no visual metrics). Yet the string length is not zero.
Conclusion. Length alone is not the only measure here. Contextual set membership is also pretty important.
Character Set membership is a very important common additional measure. Meaningful sequences are also a fairly common one. ( think SETI or crypto or captchas ) Additional more abstract context sets also exist.
So think carefully before assuming a string is only empty based on length or whitespace.

- 12,679
- 6
- 37
- 55
- (BOOL)isEmpty:(NSString *)string{
if ((NSNull *) string == [NSNull null]) {
return YES;
}
if (string == nil) {
return YES;
}
if ([string length] == 0) {
return YES;
}
if ([[string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
return YES;
}
if([[string stringByStrippingWhitespace] isEqualToString:@""]){
return YES;
}
return NO;
}

- 4,241
- 10
- 40
- 81

- 41
- 1
- 3
-
1First three conditions are redundant, and you haven't included the source for `stringByStrippingWhitespace` – mattsven Feb 20 '16 at 15:43
The best way is to use the category.
You can check the following function. Which has all the conditions to check.
-(BOOL)isNullString:(NSString *)aStr{
if([(NSNull *)aStr isKindOfClass:[NSNull class]]){
return YES;
}
if ((NSNull *)aStr == [NSNull null]) {
return YES;
}
if ([aStr isKindOfClass:[NSNull class]]){
return YES;
}
if(![[aStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]){
return YES;
}
return NO;
}

- 8,198
- 71
- 51
- 66

- 102
- 7
The best way in any case is to check the length of the given string.For this if your string is myString then the code is:
int len = [myString length];
if(len == 0){
NSLog(@"String is empty");
}
else{
NSLog(@"String is : %@", myString);
}

- 1,403
- 12
- 17
check this :
if ([yourString isEqualToString:@""])
{
NsLog(@"Blank String");
}
Or
if ([yourString length] == 0)
{
NsLog(@"Blank String");
}
Hope this will help.

- 5,454
- 7
- 41
- 70
You can easily check if string is empty with this:
if ([yourstring isEqualToString:@""]) {
// execute your action here if string is empty
}

- 33,281
- 23
- 160
- 191

- 51
- 3
I have checked an empty string using below code :
//Check if we have any search terms in the search dictionary.
if( (strMyString.text==(id) [NSNull null] || [strMyString.text length]==0
|| strMyString.text isEqual:@"")) {
[AlertView showAlert:@"Please enter a valid string"];
}

- 35,723
- 18
- 170
- 177
Its as simple as if([myString isEqual:@""])
or if([myString isEqualToString:@""])

- 1,807
- 1
- 20
- 27
//Different validations:
NSString * inputStr = @"Hey ";
//Check length
[inputStr length]
//Coming from server, check if its NSNull
[inputStr isEqual:[NSNull null]] ? nil : inputStr
//For validation in allowed character set
-(BOOL)validateString:(NSString*)inputStr
{
BOOL isValid = NO;
if(!([inputStr length]>0))
{
return isValid;
}
NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet characterSetWithCharactersInString:@".-"];
[allowedSet formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
if ([inputStr rangeOfCharacterFromSet:[allowedSet invertedSet]].location == NSNotFound)
{
// contains only decimal set and '-' and '.'
}
else
{
// invalid
isValid = NO;
}
return isValid;
}

- 934
- 2
- 8
- 23
You can have an empty string in two ways:
1) @"" // Does not contain space
2) @" " // Contain Space
Technically both the strings are empty. We can write both the things just by using ONE Condition
if ([firstNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""].length==0)
{
NSLog(@"Empty String");
}
else
{
NSLog(@"String contains some value");
}

- 209
- 2
- 4
Try the following
NSString *stringToCheck = @"";
if ([stringToCheck isEqualToString:@""])
{
NSLog(@"String Empty");
}
else
{
NSLog(@"String Not Empty");
}

- 9,889
- 11
- 50
- 74

- 59
- 7
Based on multiple answers I have created a ready to use category combining @iDevAmit and @user238824 answers.
Specifically it goes in the following order
- Check for null/nil
- Check if if string is empty using it's length count.
- Check if string is white spaces.
Header
//
// NSString+Empty.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSString (Empty)
- (BOOL)isEmptyOrWhiteSpacesOrNil;
@end
NS_ASSUME_NONNULL_END
Implementation
//
// NSString+Empty.m
#import "NSString+Empty.h"
@implementation NSString (Empty)
- (BOOL) isWhitespace{
return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
}
- (BOOL)isEmptyOrWhiteSpacesOrNil {
if(self == nil || [self isKindOfClass:[NSNull class]] || self.length==0 || [self isWhitespace] == YES) {
return YES;
}
return NO;
}
@end
/*
Credits
1. https://stackoverflow.com/a/24506942/7551807
2. https://stackoverflow.com/a/1963273/7551807
*/
Usage: of-course the function will never be triggered if your string is null. Case one is there just for extra security. I advice checking for nullability before attempting to use this method.
if (myString) {
if [myString isEmptyOrWhiteSpacesOrNil] {
// String is empty
}
} else {
// String is null
}

- 4,014
- 2
- 29
- 24
if(str.length == 0 || [str isKindOfClass: [NSNull class]]){
NSLog(@"String is empty");
}
else{
NSLog(@"String is not empty");
}

- 4,241
- 10
- 40
- 81

- 133
- 1
- 4
-
1The null check must be first. `str.length` will throw an exception if `str` is null. – Jeffery Thomas May 11 '15 at 10:53
if( [txtMobile.text length] == 0 )
{
[Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}

- 4,241
- 10
- 40
- 81

- 701
- 1
- 7
- 13