Override truth or ! operator in Objective-C

How do I override the truth-value of my class instance, or its ! operator?

For example (simplified names/usage):

MyClass variable = [MyClass alloc] initWithValue: nil];

...

if (!variable) { NSLog(@"'Not variable value' works"); }

I've searched for two possible solutions but couldn't find anything useful. In some languages i would overload an isTrue, asBool, etc function; or override the unary ! operator FOR THAT CLASS (not the main NOT operator.

My initial reaction to this problem was: You don't need to in Objective-C, you're going at it wrong. While true, I have lost over hours debugging some code that had the above (!variable) instead of

if (!variable.value) { NSLog(@"'Not variable value' works"); }

MyClass has property value among many others, which you can set or not. It defines whether or not you do something so it is common to need if (!variable.value){ NSLog(@"Warning, value not set"); }

So I want to overload the ! or isTrue function to check whether or not variable.value is set instead of merely checking if variable is linked to an address. This would make my code more readable and make my class more useable.

To be clear, in this example, variable points to an alloc-init'ed object, where variable.value = nil for example.

For example this can be done in python by overloading __ nonzero __.

As a side question that would answer this question: How does the truth value of an object work in Objective-C?

Upvotes: 1

Views: 96

Answers (2)

Ben Zotto
Ben Zotto

Reputation: 71008

You can't override these things in ObjC. ObjC behaves just like C in this regard-- object references are pointers, either valid or nil-- a nil value evaluates to NO in a boolean expression and any non-nil value will appear as YES.


The canonical check for "is this thing an invalid pointer" is if (!thing) { ... }. If you are always doing this:

if (!variable.value) ...

then perhaps variable is of type NSNumber or some object container for a primitive? It's hard to tell without context what pattern you're using and whether there's a better idiom for this.

Upvotes: 1

jscs
jscs

Reputation: 64002

An object in Objective-C has the same meaning in a boolean expression as a pointer in C, because it is a C pointer. If the pointer is NULL -- or nil for an object -- then it's false; otherwise it's true.

You can't override operators in Objective-C.

This said, !variable.value does indeed test whether value is nil (assuming that value has an object type) -- the dot operator resolves to a message send [variable value] whose return value is then negated.

Upvotes: 1

Related Questions