Feel Physics
Feel Physics

Reputation: 2783

How can I check whether parameter of function is nil or not?

I made Sender class and sender object:

Sender *sender = [[Sender alloc] init];

Then, I wrote test:

// should success
[sender upload:[UIImage imageNamed:@"test2.jpg"] withName:@"test2.jpg"];
// should fail
[sender upload:nil withName:@"test2.jpg"];

Then, I wrote nil check code:

- (void)upload:(UIImage *)image withName:(NSString *)name
{
    if ([image isEqual:nil]) {
        ...
    }
    ...
}

But nil check is ignored. How can I check whether the image parameter is nil or not? Thank you for your kindness.

Upvotes: 0

Views: 186

Answers (3)

rickster
rickster

Reputation: 126107

@yeesterbunny's answer is on point as to what you should do in this situation, but it's also good to know why.

Remember that every objc method call is a message. When you call

[objA isEqual:objB]

you're sending a message to objA asking whether it considers itself "equal" to objB.

If the "image" parameter to your method is nil, there's nothing there to send a message to. By definition, any message to nil returns nil. (And "nil" is the same as zero in an if statement.)

Moral of the story: test pointer equality with == (or !=, or implicitly as in "if (!image)") if you're looking for nil. Use isEqual: only when you want to test whether two objects (known to exist and of similar type) are semantically equal (e.g. when you want to know if two instances of NSString contain the same text).

Upvotes: 1

CRD
CRD

Reputation: 53000

Short answer, replace [image isEqual:nil] with image == nil.

Long answer, when you write:

[image isEqual:nil]

you are asking for the message isEqual: to be sent to the object whose reference is stored in the variable image.

However you don't wish to send a message to an object, you wish to determine whether the variable image contains a reference to an object or not. To do this you need to compare the value of your reference with the "no reference" value - which is written nil. The value comparison operator in Objective-C (and C et al) is == so you need to test:

image == nil

Now you might ask why did the code you have execute without error, just not producing the result you expected, given that there is no object to send a message to? Objective-C supports sending messages to "no object", aka nil, and returns the "zero" value for the result type, i.e. 0, nil etc. When converted to a boolean value, as in your if statement, a "zero" value produces NO.

HTH

Upvotes: 2

yeesterbunny
yeesterbunny

Reputation: 1847

Try

if(!image)

or

if(image == nil)

Upvotes: 3

Related Questions