First off I confess my ignorance, I\'ve learned everything I know about Objective-C in the few months I\'ve been working on my project. I also find it utterly frustrating ho
In some cases, such as missing keys in NSUserDefaults, you get back the literal @"" as an empty string.
Here's my safe check for an NSNumber.
Note the check for it being an NSNumber occurs first because NSNumber doesn't understand isEqualToString
id savedPin = [[NSUserDefaults standardUserDefaults] valueForKey:@"blah"]; // don't assume is created so don't type as NSNumber*
if ( ![savedPin isKindOfClass:[NSNumber class]] && [savedPin isEqualToString:@""]) {
Use [shoObject class]
to get the class of an object; so, to test shoObject
's class, you would use
[shoObject isKindOfClass:[NSString class]];
Once you've sorted out what markers define an empty string or NSNumber, you can create a macro. I do with this by keeping an IsEmpty macro in a file called CommonMacros.h. Here's the code:
//Thanks Wil
//http://wilshipley.com/blog/2005/10/pimp-my-code-interlude-free-code.html
static inline BOOL IsEmpty(id thing) {
return thing == nil
|| ([thing isEqual:[NSNull null]]) //JS addition for coredata
|| ([thing respondsToSelector:@selector(length)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [(NSArray *)thing count] == 0);
}
Then, after importing CommonMacros.h, you can call the function like this:
if (IsEmpty(shotIndex)) {
//do stuff
}
This should take care of this problem, and will also work on strings, arrays, etc, as you can see from the code. Thanks to Wil Shipley!
In Objective-c, it's nil
not null
. So:
if (shotIndex != nil) {
// its not nil
}