Awesome-o
Awesome-o

Reputation: 2070

comparing nil to integer in Objective-C

In the following case where string is an NSString

if (string.length < 1)
{
    return;
}

and string turns out to be nil the if statement will still evaluate correctly because in this case nil evaluates to 0.

However, is this recommended practice (by Clang or Apple) and are there any arguments against this and doing something closer to:

if (!string || string.length < 1)
{
    return;
}

Upvotes: 0

Views: 336

Answers (3)

MCMatan
MCMatan

Reputation: 8833

Some cases,for example working with strings that are made from response of requests, you should check the string, is a string, and not data!

   NSString *string;
if ([string isKindOfClass:[NSString class]]) {
    //
} 

Cheers!

Upvotes: -1

rmaddy
rmaddy

Reputation: 318794

It's very common to do something like:

if (string.length) {
    // string is not nil and the string has a non-zero length
} else {
    // either string is nil or the length is zero
}

There is no need, in such a case, to check to see if string is nil or not.

When string is nil, you end up doing [nil length]. Calling any method on a nil pointer results in a value of "zero". How the "zero" is interpreted depends on the method's return type.

Primitive types appear as 0. BOOL appears as NO. Pointers appear as nil.

Upvotes: 4

Wain
Wain

Reputation: 119031

I'd say it's fine. Your alternate line is harder to understand at a glance and relies on the same logic (nil == 0) as the original line.

Upvotes: 0

Related Questions