How do I test if a string is empty in Objective-C? - ios

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

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.

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

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!");

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

You should better use this category:
#implementation NSString (Empty)
- (BOOL) isWhitespace{
return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
}
#end

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

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.

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

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

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?

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
}

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 ...

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.

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.

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

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.

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

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

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

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

if (string.length == 0) stringIsEmpty;

check this :
if ([yourString isEqualToString:#""])
{
NsLog(#"Blank String");
}
Or
if ([yourString length] == 0)
{
NsLog(#"Blank String");
}
Hope this will help.

You can easily check if string is empty with this:
if ([yourstring isEqualToString:#""]) {
// execute your action here if string is empty
}

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"];
}

Its as simple as if([myString isEqual:#""]) or if([myString isEqualToString:#""])

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

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

Try the following
NSString *stringToCheck = #"";
if ([stringToCheck isEqualToString:#""])
{
NSLog(#"String Empty");
}
else
{
NSLog(#"String Not Empty");
}

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
}

if(str.length == 0 || [str isKindOfClass: [NSNull class]]){
NSLog(#"String is empty");
}
else{
NSLog(#"String is not empty");
}

Related

Prevent Users from Entering Multiple Decimals In Objective-C

I am making an only number input app (still) in which users press a button, I store a value into a string to display in a label.
Works great for the most part, except I cannot figure out how to prevent users from entering more than one decimal in a single string. .
I looked at this Stack overflow question, but trying to amend the code for my own just resulted in a whole bunch of errors. Does anyone have any advice?
- (void)numberBtn:(UIButton *)sender {
if (self.sales.text.length < 10) {
if(self.sales.text.length != 0){
NSString *lastChar = [self.sales.text substringFromIndex:[self.sales.text length] - 1];
if([lastChar isEqualToString:#"."] && [sender.titleLabel.text isEqualToString:#"."] && [sender.titleLabel.text stringByAppendingString:#"."]){
return;
}
if ([lastChar isEqualToString:#""] && [sender.titleLabel.text isEqualToString:#""]){
self.numbers = #"0.";
}
if ([self.sales.text rangeOfString:#"."].length > 0) {
NSArray *array = [self.sales.text componentsSeparatedByString:#"."];
if (array.count == 2) {
NSString *decimal = array.lastObject;
if (decimal.length > 2) {
return;
}
}
}
}
self.numbers = [NSString stringWithFormat:#"%#%#",self.numbers,sender.titleLabel.text];
self.sales.text = self.numbers;
}
}
Two steps...
Check to see if the button is a decimal .
if yes, see if the current label text already contains a .
If it does, return. If not, continue processing your button input:
- (void)numberBtn:(UIButton *)sender {
NSString *btnTitle = sender.currentTitle;
NSString *curText = self.sales.text;
if ([btnTitle isEqualToString:#"."]) {
if ([curText containsString:#"."]) {
NSLog(#"%# : Already has a decimal point!", curText);
return;
}
}
// whatever else you want to do with the input...
}

JSON, Obj C, Safety and null checks

I am working on an app that retrieves dense multi layered business objects back from a webservice. I have in Obj C created classes that represent and map the Webservice object properly ( ie : user object, post object, group object )
Now I am getting data back as a json, and for some data points the response comes back with some parts of the data is null, or some portions of the object are just not there ( like a user object with no last name). Naturally I would start checking if the
JSONRESPONSE
Has value for firstname, and then lastname, and then city, etc , etc.
Obviously there is a lot of redundancy in this, and I don;t want to write the same check over and over again, but thinking of a class method in a utilities class I have.
Anyone has ideas on this? whats the best approach to do this?
Thanks.
One way to deal with it is to have your classes use NSKeyValueCoding, and then setup some validation method that takes some data structure (e.g. array of attribute names) and check for required attributes, default values, etc. The rest is up to you, if you want to do some logging, set default values, etc. The data structure really depends on how much validation you need.
You can try by adding categories which do the null & nil check for you. To avoid crash because of nil insertions you can return empty strings. For instance, below is a category on NSDictionary that helps retrieving non nil/null strings.
- (id)nullSafeObjectForKey:(NSString *) iKey {
id retrievedValue = [self objectForKey:iKey];
return ([retrievedValue isKindOfClass:[NSNull class]] || retrievedValue == nil) ? #"" : retrievedValue;
}
You can use this method for NSString,NSArray,NSDictionary,NSData,UIImage
- (BOOL)isObjectEmpty:(id)object {
if ([object isKindOfClass:[NSNull class]] || object == nil) {
return YES;
}
if ([object isKindOfClass:[NSString class]]) {
if (object == nil || ([object respondsToSelector:#selector(length)] && [(NSString *)object length] == 0)) {
return YES;
}
}
else if ([object isKindOfClass:[NSArray class]]) {
if (object == nil || ([object respondsToSelector:#selector(count)] && [(NSArray *)object count] == 0)) {
return YES;
}
}
else if ([object isKindOfClass:[NSDictionary class]]) {
if (object == nil || ([object respondsToSelector:#selector(count)] && [(NSDictionary *)object count] == 0)) {
return YES;
}
}
else if ([object isKindOfClass:[NSData class]]) {
if (object == nil || ([object respondsToSelector:#selector(length)] && [(NSData *)object length] == 0)) {
return YES;
}
}
else if ([object isKindOfClass:[UIImage class]]) {
if (object == nil) {
return YES;
}
}
return NO;
}

How to detect if NSString contains a particular character or not?

i have one NSString object , for ex:- ($45,0000)
Now i want to find if this string contains () or not
How can i do this?
Are you trying to find if it contains at least one of ( or )? You can use -rangeOfCharacterFromSet::
NSCharacterSet *cset = [NSCharacterSet characterSetWithCharactersInString:#"()"];
NSRange range = [mystr rangeOfCharacterFromSet:cset];
if (range.location == NSNotFound) {
// no ( or ) in the string
} else {
// ( or ) are present
}
The method below will return Yes if the given string contains the given char
-(BOOL)doesString:(NSString *)string containCharacter:(char)character
{
return [string rangeOfString:[NSString stringWithFormat:#"%c",character]].location != NSNotFound;
}
You can use it as follows:
NSString *s = #"abcdefg";
if ([self doesString:s containCharacter:'a'])
NSLog(#"'a' found");
else
NSLog(#"No 'a' found");
if ([self doesString:s containCharacter:'h'])
NSLog(#"'h' found");
else
NSLog(#"No 'h' found");
Output:
2013-01-11 11:15:03.830 CharFinder[17539:c07] 'a' found
2013-01-11 11:15:03.831 CharFinder[17539:c07] No 'h' found
- (bool) contains: (NSString*) substring {
NSRange range = [self rangeOfString:substring];
return range.location != NSNotFound;
}
I got a generalized answer to your question which I was using in my code. This code includes the following rules:
1. No special characters
2. At least one capital and one small English alphabet
3. At least one numeric digit
BOOL lowerCaseLetter,upperCaseLetter,digit,specialCharacter;
int asciiValue;
if([txtPassword.text length] >= 5)
{
for (int i = 0; i < [txtPassword.text length]; i++)
{
unichar c = [txtPassword.text characterAtIndex:i];
if(!lowerCaseLetter)
{
lowerCaseLetter = [[NSCharacterSet lowercaseLetterCharacterSet] characterIsMember:c];
}
if(!upperCaseLetter)
{
upperCaseLetter = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:c];
}
if(!digit)
{
digit = [[NSCharacterSet decimalDigitCharacterSet] characterIsMember:c];
}
asciiValue = [txtPassword.text characterAtIndex:i];
NSLog(#"ascii value---%d",asciiValue);
if((asciiValue >=33&&asciiValue < 47)||(asciiValue>=58 && asciiValue<=64)||(asciiValue>=91 && asciiValue<=96)||(asciiValue>=91 && asciiValue<=96))
{
specialCharacter=1;
}
else
{
specialCharacter=0;
}
}
if(specialCharacter==0 && digit && lowerCaseLetter && upperCaseLetter)
{
//do what u want
NSLog(#"Valid Password %d",specialCharacter);
}
else
{
NSLog(#"Invalid Password %d",specialCharacter);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Please Ensure that you have at least one lower case letter, one upper case letter, one digit and No Any special character"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
Why to always use for NSCharactorSet ?? this is simple and powerful solution
NSString *textStr = #"This is String Containing / Character";
if ([textStr containsString:#"/"])
{
NSLog(#"Found!!");
}
else
{
NSLog(#"Not Found!!");
You can use
NSString rangeOfString: (NSString *) string
See here: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html%23//apple_ref/occ/instm/NSString/rangeOfString:
If the NSRange comes back with property 'location' equal to NSNotFound, then the string does not contain the passed string (or character).

if statement issue in drawRect

Yes, yes. Shame on me. I am trying to draw in UIView and my code is:
NSString *str;
if(kmObj.metal!=#"" && kmObj.metalName2!=#"" && kmObj.metalname3!=#"")
{
str=[NSString stringWithFormat:#"%# + %# + %#",kmObj.metal,kmObj.metalName2,kmObj.metalname3];
}
if(kmObj.metal!=#"" && kmObj.metalName2!=#"" && kmObj.metalname3==#"")
{
str=[NSString stringWithFormat:#"%# + %#",kmObj.metal,kmObj.metalName2];
}
if(kmObj.metal!=#"" && kmObj.metalName2==#"" && kmObj.metalname3==#"")
{
str=[NSString stringWithFormat:#"%#",kmObj.metal];
}
[str drawAtPoint:CGPointMake(10.0,234.0)
forWidth:200
withFont:[UIFont systemFontOfSize:20.0]
minFontSize:20.0
actualFontSize:NULL
lineBreakMode:UILineBreakModeTailTruncation
baselineAdjustment:UIBaselineAdjustmentAlignBaselines];
So, this code suppose to check if the Object contains more than one metal name record. If so, than it has to format string to form: Au+Ag+Cu ... My problem is that in output draw I can't get rid of the + signs where I don't need them. Is there something wrong in my if statement?
Instead of if (string != #""), use ![string isEqualToString:#""] or perhaps ([string length] > 0). You need to make sure you are performing a value comparison, not a pointer comparison.
Anyway, I would write code like this:
NSString *outputString = #"";
if ([firstString length] > 0) {
outputString = [outputString stringByAppendingString:firstString];
}
if ([secondString length] > 0) {
outputString = [outputString stringByAppendingFormat:#" + %#", secondString];
}
if ([thirdString length] > 0) {
outputString = [outputString stringByAppendingFormat:#" + %#", thirdString];
}
With this technique, you check each string individually, and only include a plus sign when you know another valid string will follow it.
String comparisons should take the form: [stringA isEqualToString:stringB]
From the docs: When you know both objects are strings, this method is a faster way to check equality than isEqual:
Plus, == for strings is weird anyways - they are non-primitives and you're wanting a value comparison.
Also, you should take into account the possibility of having nil and/or [NSNull null] values (depending on where these values are sourced). Your current test of whether or not they are equal to empty strings doesn't take this into account.
Did you mean that you don't want the "+" sign? Then don't put it in your NSString.
So instead of
str = [NSString stringWithFormat:#"%# + %# + %#",kmObj.metal,kmObj.metalName2,kmObj.metalname3];
do
str = [NSString stringWithFormat:#"%# %# %#",kmObj.metal,kmObj.metalName2,kmObj.metalname3];
also use [kmObj.metal isEqualToString:#""] for your string comparison

iOS can't check if object is null

So I have the following code:
- (IBAction)doSomething
{
if (txtName.text != (id)[NSNull null] || txtName.text.length != 0 ) {
NSString *msg = [[NSString alloc] initWithFormat:#"Hello, %#", txtName.text];
[lblMessage setText:msg];
}
}
txtName is an UITextField, what I'm doing wrong? I'm trying to display some text only when the user types something in the box.
Best Regards,
Text in a text field is a NSString instance or nil value, it is never equal to the instance of NSNull class (which is not the same as nil). So as 1st comparison is always true then the whole if-condition evaluates to true and message appears.
You could correct your if condition to
if (txtName.text != nil && txtName.text.length != 0 )
or, as sending length message to the nil will return 0 anyway just have
if (txtName.text.length != 0 )
although I usually use the 1st option with 2 comparisons
if (txtName.text != (id)[NSNull null] || txtName.text.length != 0 ) {
Read it as "If the text is null or the length is not 0"
txtName.text is never nil (you can just compare against nil for a null check, by the way) - the text box always holds some text, even if it's empty. So the first disjunct is always true, and the box will always appear.
I got the same problem like you. This problem relates to NSNull class. And here is my code to check object is null.
NSString* text;
if([text isKindOfClass:[NSNull class]])
{
//do something here if that object is null
}
Hope this can help.
#define SAFESTRING(str) ISVALIDSTRING(str) ? str : #""
#define ISVALIDSTRING(str) (str != nil && [str isKindOfClass:[NSNull class]] == NO)
#define VALIDSTRING_PREDICATE [NSPredicate predicateWithBlock:^(id evaluatedObject, NSDictionary *bindings) {return (BOOL)ISVALIDSTRING(evaluatedObject);}]
SAFESTRING(PASS_OBJECT OR STRING);
Solution found! ![txtName.text isEqualToString:#""]
- (IBAction)doSomething
{
if (![txtName.text isEqualToString:#""]){
NSString *msg = [[NSString alloc] initWithFormat:#"Hello, %#", txtName.text];
[lblMessage setText:msg];
}
}
Please try this:
when value of myObj is nil or < null>
if([myObj isEqual:[NSNull class]] || !myObj) {
// your code
}

Resources