String isNullOrEmpty as a category - iphone

I'm trying to create a method which checks for a null/nil/empty string, and I'm trying to get it working as a category but having no luck.
I'm using this code, based on answers in this topic:
#implementation NSString (NSStringExtension)
- (BOOL)isNullOrEmpty {
return self == nil ||
self == (id)[NSNull null] ||
[#"" isEqualToString:self] ||
[[self stringByReplacingOccurrencesOfString:#" " withString:#""] length] == 0||
[self isEqualToString:#"(null)"]
|| ([self respondsToSelector:#selector(length)] && [(NSData *) self length] == 0)
|| ([self respondsToSelector:#selector(count)] && [(NSArray *) self count] == 0)
|| [[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0;
}
#end
Yet when I try to use this this is what I get:
NSLog([#"" isNullOrEmpty] ? #"1":#"0"); // prints 1
NSString *s1 = nil;
NSLog([s1 isNullOrEmpty] ? #"1":#"0"); // prints 0
NSLog([args.itemName isNullOrEmpty] ? #"1":#"0"); // prints 0
NSLog([(NSString*)nil isNullOrEmpty] ? #"1":#"0"); // prints 0
This is baffling me, and I can only assume that some combination of iOS5/ARC is causing the nil object to be coerced to a blank string/pointer. The debugger shows the string as 0x0, yet when I use my isNullOrEmpty method, I get false.

return self == nil
This can never happen. If you try to send isNullOrEmpty (or any other message) to nil, nothing happens (objc_msgSend(), the function responsible for message dispatch, checks for a nil reciever as one of the first things it does and aborts).
self == (id)[NSNull null]
This will also never happen. If you send isNullOrEmpty to an object that's an instance of NSNull, your method here, which is a method on NSString, will not be called. Instead, NSNull's version (which probably doesn't exist) will be.
Likewise, ([self respondsToSelector:#selector(count)] && [(NSArray *) self count]) is never going to happen. If the object is an NSArray, then isNullOrEmpty will never run, because, again, it's a method of NSString.
Correspondingly, [(NSData *) self length] doesn't do what you think it does. NSString instances do respond to length, but casting the object to NSData doesn't use the NSData version of the method -- it still ends up as the NSString version of length, because the object actually is an NSString (casting only happens at compile-time; it can't change anything at run-time).
[self isEqualToString:#"(null)"]
Here you appear to be checking for nil again, but you are being misled by the representation that NSLog chooses when it prints nil:
NSLog(#"%#", nil);
This displays (null) in the console, but that doesn't mean that the object itself is a string with those characters. NSLog just chooses that string to display for nil.*
Several of the things you are doing would require this to be in a category on NSObject, so that the method would in fact be called even if the object was not an NSString.
To check for a string consisting only of whitespace, all you need is the comparison to the empty string #"" after trimming whitespace:
NSString * trimmedSelf = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
// Then either:
[trimmedSelf isEqualToString:#""];
// Or:
([trimmedSelf length] == 0);
*And even better, doing NSLog(#"%#", [NSNull null]); displays <null> (angle brackets instead of parentheses), wonderfully confusing the first few times you encounter NSNull.

Another approach can be to define a simple macro.
#define NSStringIsNullOrEmpty(str) ((str==nil) || [(str) isEqualToString:#""])
It's simple and effective. If you do not like macros you can always convert it to a function call without affecting the rest of your code.
-- Update:
#Bryan has raised a good point. An inline function is a great way to go. Here is an updated macro that will evaluate str only once.
#define NSStringIsNullOrEmpty(str) ({ NSString *_str=(str); ((tmp==nil) || [tmp isEqualToString:#""]);})

In Objective-C, sending a message to nil will always return 0 (or NO, a zeroed-out struct, NULL, etc., depending on the declared return type). The isNullOrEmpty method that you wrote won't actually be invoked when you send isNullOrEmpty to nil. See the accepted answer to Sending a message to nil? for more information.
Perhaps you could change your method to be isNotNullOrEmpty. Then a return value of 0 when sending isNotNullOrEmpty to nil will make sense.

You aren't calling your method, but sending a message to nil.

This is expected behavior. You are sending a message to nil after all. So it is returning either nil (or some other 0 value). Which short circuits to false so that '0' is printed in the cases shown below:
NSLog([s1 isNullOrEmpty] ? #"1":#"0"); // prints 0
NSLog([(NSString*)nil isNullOrEmpty] ? #"1":#"0"); // prints 0
You can even confirm your message is not being called for those cases by setting a breakpoint in your new category method.

Like others have said, calling [nil isNullOrEmpty]; will not actually run your method. The nil object is just that : empty itself.
As a solution, I'd like to say that it's not because you're in an Object-Oriented language that you must never use functions.
BOOL IsStringNilOrEmpty(NSString*)str
{
return str == nil ||
str == null ||
[#"" isEqualToString:str] ||
[[str stringByReplacingOccurrencesOfString:#" " withString:#""] length] == 0||
[str isEqualToString:#"(null)"]
|| ([str respondsToSelector:#selector(length)] && [(NSData *) str length] == 0)
|| ([str respondsToSelector:#selector(count)] && [(NSArray *) str count] == 0)
|| [[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0;
}

actually I just fixed this problem by turning it around like so
-(BOOL) isNotNullOrWhiteSpace
{
return [self length] != 0 && [[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] != 0;
}
so instead of isNullOrWhiteSpace it's isNotNullOrWhiteSpace.

Here's my method of checking null/empty
-(NSString*)NULLInputinitWithString:(NSString*)InputString
{
if( (InputString == nil) ||(InputString ==(NSString*)[NSNull null])||([InputString isEqual:nil])||([InputString length] == 0)||([InputString isEqualToString:#""])||([InputString isEqualToString:#"(NULL)"])||([InputString isEqualToString:#"<NULL>"])||([InputString isEqualToString:#"<null>"]||([InputString isEqualToString:#"(null)"])||([InputString isEqualToString:#"NULL"]) ||([InputString isEqualToString:#"null"])))
return #"";
else
return InputString ;
}

Have you thought about creating a class method on a category that extends NSString?
NSString+NSStringExtensions.h
#import <Foundation/Foundation.h>
#interface NSString(NSStringExtensions)
+(BOOL)isNilOrEmpty:(NSString*)string;
#end
NSString+NSStringExtensions.m
#import "NSString+NSStringExtensions.h"
#implementation NSString(NSStringExtensions)
+(BOOL)isNilOrEmpty:(NSString*)string
{
if (nil == string)
{
return YES;
}
if (string.length == 0)
{
return YES;
}
return NO;
}
#end
Then you use it like this:
#import "NSString+NSStringExtensions.h"
...
NSLog([NSString isNilOrEmpty:#""] ? #"1":#"0");

Related

How to make a if statement with NSNull in objective-c

I am develop a iPhone application, in which i need to use JSON to receive data from server.
In the iPhone side, I convert the data into NSMutableDictionary.
However, there is a date type data are null.
I use the following sentence to read the date.
NSString *arriveTime = [taskDic objectForKey:#"arriveTime"];
NSLog(#"%#", arriveTime);
if (arriveTime) {
job.arriveDone = [NSDate dateWithTimeIntervalSince1970:[arriveTime intValue]/1000];
}
When the arriveTime is null, how can i make the if statement. I have tried [arriveTime length] != 0, but i doesn't work, because the arriveTime is a NSNull and doesn't have this method.
the NSNull instance is a singleton. you can use a simple pointer comparison to accomplish this:
if (arriveTime == nil) { NSLog(#"it's nil"); }
else if (arriveTime == (id)[NSNull null]) { // << the magic bit!
NSLog(#"it's NSNull");
}
else { NSLog(#"it's %#", arriveTime); }
alternatively, you could use isKindOfClass: if you find that clearer:
if (arriveTime == nil) { NSLog(#"it's nil"); }
else if ([arriveTime isKindOfClass:[NSNull class]]) {
...
In a single line
arriveTime ? job.arriveDone = [NSDate dateWithTimeIntervalSince1970:[arriveTime intValue]/1000]; : NSLog(#"Arrive time is not yet scheduled");

NSString contains : <null> and is crashing my app

I've an NSString thats populated from some data returned via JSON.
The code works great under normal circumstances but there is an occasion when i get returned by the JSON.
When i do a check to see if my NSString == nil or == null it fails the test.
But the fact that the NSString contains crashes my app.
So does have some special meaning in Objective C? Or should i just do a string compare and see if the string is equal to rather than being nil and handle it that way.
This has me a little confused.
Many Thanks,
Code
<null> is what NSNull returns for its -description method. You need to also check for
myString == [NSNull null]
in this case.
Additional info: IIRC the common Objective-C JSON stuff will use [NSNull null] for nulls in the JSON structure, to differentiate the value from one that simply isn't there.
NSString * is just a pointer to a NSString object.
To test for null pointer:
NSString *str;
if (str) {
// str points to an object
if ([str length] == 0) {
// string is empty
}
} else
// str points to nothing
}
If you want to check for whitespace, you can trim the NSString with stringByTrimmingCharactersInSet.
You could check to see if it's null by.
if ([str isKindOfClass:[NSNull class]]) {
// str is null.
}
I did it this way:
if([string isKindOfClass:[NSNull class]]) {
NSLog(#"This is JSON null");
} else {
NSLog(#"This is a string, do what you wanna do with it");
}

[NSNull isEqualToString:]

Im trying to set a string to "No Display name if [object objectForKey#"display_name"] is NULL". It crashing with this in the log
2011-06-16 10:58:36.251 BV API[15586:ef03] displayNameType is: NSNull
2011-06-16 10:58:36.251 BV API[15586:ef03] +[NSNull isEqualToString:]: unrecognized selector sent to class 0x1228c40
2011-06-16 10:58:36.253 BV API[15586:ef03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSNull isEqualToString:]: unrecognized selector sent to class 0x1228c40'
*** First throw call stack:
(0x1198f1c 0x132b52e 0x119bb2b 0x10f3076 0x10f2bb2 0x116d9 0x112ad 0x8b0e17 0x8b9783 0x8b43ae 0x8b9d20 0xb6312b 0x815c35 0xac2e1e 0x8b7583 0x8b771d 0x8b775d 0xc1b5 0x7ed84c 0x7ed7e2 0x89477a 0x894c4a 0x893ee4 0x813002 0x81320a 0x7f960c 0x7ecd52 0x211b8f6 0x116831a 0x10c3d07 0x10c1e93 0x10c1750 0x10c1671 0x211a0c3 0x211a188 0x7eac29 0x1b29 0x1aa5)
terminate called throwing an exceptionsharedlibrary apply-load-rules all
Current language: auto; currently objective-c
NSString *displayNameType = (NSString *)[[object objectForKey:#"display_name"] class ];
NSLog(#"displayNameType is: %#", displayNameType);
NSString *displayNameString = [NSString stringWithFormat:#"%#", [object objectForKey:#"display_name"]];
displayNameString = [displayNameString uppercaseString];
if ([displayNameType isEqualToString:#"NSNull"]) {
NSLog(#"dnt is null");
NSString *displayNameString = #"No Display Name";
displayNameString = [displayNameString uppercaseString];
}
A cast will not change an object class (type).
You have to manage the case when your value is [NSNull null] with something like :
id displayNameTypeValue = [object objectForKey:#"display_name"];
NSString *displayNameType = #"";
if (displayNameTypeValue != [NSNull null])
displayNameType = (NSString *)displayNameTypeValue;
I created a category on NSNull, works well for me:
#interface NSNull (string)
-(BOOL) isEqualToString:(NSString *) compare;
#end
#implementation NSNull (string)
-(BOOL) isEqualToString:(NSString *) compare {
if ([compare isKindOfClass:[NSNull class]] || !compare) {
NSLog(#"NSNull isKindOfClass called!");
return YES;
}
return NO;
}
#end
You might want something like this:
NSString *displayNameType = NSStringFromClass([[object objectForKey:#"display_name"] class]);
And btw in your question, it shouldn't read "if it's NULL", but rather "if it's an NSNull instance".
I'll throw in my answer to clarify a bit. The problem is that the object in the NSDictionary has [NSNull null] value (slightly different to both nil and NULL). The issue comes from some libraries (a particular JSON parser comes to my mind) set the value for some keys with NULL value to [NSNull null]. Why? Because sometimes it is needed to differentiate in a NSDictionary the case when a key is not present from the case when the key has NULL value. In an NSDictionary there is no way of telling, but JSON structures do convey such difference. When you get a a variable that comes from a library or parser that does that the value may be [NSNull null]. NSNull is a singleton thus just checking for equality (pointer equality) is enough. For example I would do:
NSString *value = [object objectForKey:#"display_name"];
if (value && value != [NSNull null]){
// Here I have the value I expect
// Do something
}else{
// The value is null ... don't display
}
To my experience, the font may be well missing. If you got the problem, you could check where you set the new font and if it exists.
let font = UIFont.init(name:"YOUR_FONT_NAME", size: 16) -> is it nil or not ?
Detect whether or not the object is null instead of trying to infer from the class name.
// if you're key may not exist (NSDictionary will return nil... not sure what type
// you are using
if (![object objectForKey:#"display_name"]){
// ...
}
// or if the value may actually be an NSNull object
if ([[object objectForKey:#"display_name"] == (id)[NSNull null]){
// ...
}
I haven't tested the second argument, but look here for more about testing null.
I solved this by doing a check against [NSNull null]. The code I used in my app:
_lblBusinessName.text = _business.BusinessName != [NSNull null] ? _business.BusinessName : #"";
However XCode threw some warnings so to get rid of those I casted to an NSObject* type, like this:
_lblBusinessName.text = **(NSObject*)**_business.BusinessName != [NSNull null] ? _business.BusinessName : #"";

NSString is empty

How do you test if an NSString is empty? or all whitespace or nil? with a single method call?
You can try something like this:
#implementation NSString (JRAdditions)
+ (BOOL)isStringEmpty:(NSString *)string {
if([string length] == 0) { //string is empty or nil
return YES;
}
if(![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
//string is all whitespace
return YES;
}
return NO;
}
#end
Check out the NSString reference on ADC.
This is what I use, an Extension to NSString:
+ (BOOL)isEmptyString:(NSString *)string;
// Returns YES if the string is nil or equal to #""
{
// Note that [string length] == 0 can be false when [string isEqualToString:#""] is true, because these are Unicode strings.
if (((NSNull *) string == [NSNull null]) || (string == nil) ) {
return YES;
}
string = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([string isEqualToString:#""]) {
return YES;
}
return NO;
}
I use,
+ (BOOL ) stringIsEmpty:(NSString *) aString {
if ((NSNull *) aString == [NSNull null]) {
return YES;
}
if (aString == nil) {
return YES;
} else if ([aString length] == 0) {
return YES;
} else {
aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([aString length] == 0) {
return YES;
}
}
return NO;
}
+ (BOOL ) stringIsEmpty:(NSString *) aString shouldCleanWhiteSpace:(BOOL)cleanWhileSpace {
if ((NSNull *) aString == [NSNull null]) {
return YES;
}
if (aString == nil) {
return YES;
} else if ([aString length] == 0) {
return YES;
}
if (cleanWhileSpace) {
aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([aString length] == 0) {
return YES;
}
}
return NO;
}
I hate to throw another log on this exceptionally old fire, but I'm leery about editing someone else's answer - especially when it's the selected answer.
Jacob asked a follow up question: How can I do this with a single method call?
The answer is, by creating a category - which basically extends the functionality of a base Objective-C class - and writing a "shorthand" method for all the other code.
However, technically, a string with white space characters is not empty - it just doesn't contain any visible glyphs (for the last couple of years I've been using a method called isEmptyString: and converted today after reading this question, answer, and comment set).
To create a category go to Option+Click -> New File... (or File -> New -> File... or just command+n) -> choose Objective-C Category. Pick a name for the category (this will help namespace it and reduce possible future conflicts) - choose NSString from the "Category on" drop down - save the file somewhere. (Note: The file will automatically be named NSString+YourCategoryName.h and .m.)
I personally appreciate the self-documenting nature of Objective-C; therefore, I have created the following category method on NSString modifying my original isEmptyString: method and opting for a more aptly declared method (I trust the compiler to compress the code later - maybe a little too much).
Header (.h):
#import <Foundation/Foundation.h>
#interface NSString (YourCategoryName)
/*! Strips the string of white space characters (inlcuding new line characters).
#param string NSString object to be tested - if passed nil or #"" return will
be negative
#return BOOL if modified string length is greater than 0, returns YES;
otherwise, returns NO */
+ (BOOL)visibleGlyphsExistInString:(NSString *)string;
#end
Implementation (.m):
#implementation NSString (YourCategoryName)
+ (BOOL)visibleGlyphsExistInString:(NSString *)string
{
// copying string should ensure retain count does not increase
// it was a recommendation I saw somewhere (I think on stack),
// made sense, but not sure if still necessary/recommended with ARC
NSString *copy = [string copy];
// assume the string has visible glyphs
BOOL visibleGlyphsExist = YES;
if (
copy == nil
|| copy.length == 0
|| [[copy stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0
) {
// if the string is nil, no visible characters would exist
// if the string length is 0, no visible characters would exist
// and, of course, if the length after stripping the white space
// is 0, the string contains no visible glyphs
visibleGlyphsExist = NO;
}
return visibleGlyphsExist;
}
#end
To call the method be sure to #import the NSString+MyCategoryName.h file into the .h or .m (I prefer the .m for categories) class where you are running this sort of validation and do the following:
NSString* myString = #""; // or nil, or tabs, or spaces, or something else
BOOL hasGlyphs = [NSString visibleGlyphsExistInString:myString];
Hopefully that covers all the bases. I remember when I first started developing for Objective-C the category thing was one of those "huh?" ordeals for me - but now I use them quite a bit to increase reusability.
Edit: And I suppose, technically, if we're stripping characters, this:
[[copy stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0
Is really all that is needed (it should do everything that category method does, including the copy), but I could be wrong on that score.
I'm using this define as it works with nil strings as well as empty strings:
#define STR_EMPTY(str) \
str.length == 0
Actually now its like this:
#define STR_EMPTY(str) \
(![str isKindOfClass:[NSString class]] || str.length == 0)
Maybe you can try something like this:
+ (BOOL)stringIsEmpty:(NSString *)str
{
return (str == nil) || (([str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]).length == 0);
}
Based on the Jacob Relkin answer and Jonathan comment:
#implementation TextUtils
+ (BOOL)isEmpty:(NSString*) string {
if([string length] == 0 || ![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
return YES;
}
return NO;
}
#end
Should be easier:
if (![[string stringByReplacingOccurencesOfString:#" " withString:#""] length]) { NSLog(#"This string is empty"); }

What's wrong with this method?

I'm getting a warning: "Return makes pointer from integer without a cast" for this method...
+(BOOL *)getBoolFromString:(NSString *)boolStr
{
if(boolStr == #"true" || boolStr == #"1"){
return YES;
}
return NO;
}
BOOL is not a class or object, so returning a pointer to a BOOL is not the same as returning a BOOL.
You should remove the * in +(BOOL *) and everything will be ok.
Besides what #Jasarien and #jlehr have said, you have a problem with this:
(boolStr == #"true" || boolStr == #"1")
That's doing pointer comparison, not object equality. You want:
([boolStr isEqualToString:#"true"] || [boolStr isEqualToString:#"1"])
To get a BOOL from an NSString, all you need to do is send a -boolValue message, like so:
NSString *myString = #"true"; // or #"YES", etc.
BOOL bool = [myString boolValue];