I have an NSString that is stored in Core Data. It is optional, which I believe in the sqlite db means it can be null. I have a convenience method I call ‘isEmptyOrWhitespace’ shown here:
- (BOOL)isEmptyOrWhiteSpace {
return self == nil ||
self.length == 0 ||
[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length == 0;
}
When my string from Core Data is nil, it doesn’t seem to call this method, that is the breakpoints are never hit. This is particularly annoying because a code chunk like this:
if(![string isEmptyOrWhitespace]) {
[string doSomething];
}
doSomething is being run if string is nil, obviously not my intent. Is there a way to get around this without checking if my string is nil before calling a method on it? Or is this a “feature” of Objective-C that methods aren’t run on nil objects?
If
stringisnil, then[string isEmptyOrWhitespace]does nothing, because sending messages tonilis a no-op.EDIT: As @Jim pointed out, this answer is not correct.
[nil isEmptyOrWhitespace]returns0, and that is the real reason that theif ()block is not executed ifstring = nil.