Show Menu

Do you have a job opening?

Submit your 30 day Job Listing for FREE

This is a quick tip that will allow you to check whether an NSString is empty.

This quick tip has been helped by StackOverflow and Wil Shipley

The quickest thing to do is you can check if the length of the string is 0. Like so:


[string length] == 0

This will check if it’s a valid but empty string (@””) as well as if its nil, since calling length on nil will also return 0.

I’ll take this opportunity to include a pointer to Wil Shipley’s generalized isEmpty:


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);
}

Now, Whilst The first approach (Wil Shipley) is valid, it 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!");

I hoe that helps. If you have any comments or suggestions then please leave them below.

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly


Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.


Written by:

I work in the shadows. You can thank me by being a good soul.

Comments

comments