Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is if (variable) the same as if (variable != nil) in Objective-C

I am getting a EXC_BAD_ACCESS (SIGBUS) on this line in my iPhone project:

if (timeoutTimer) [timeoutTimer invalidate];

The thing that has me stumped is that I don't understand how that line could crash, since the if statement is meant to be checking for nil. Am I misunderstanding the way Objective-C works, or do line numbers in crash statements sometime have the wrong line in them?

like image 359
rustyshelf Avatar asked Feb 11 '09 01:02

rustyshelf


People also ask

How do you check if a string is nil in Objective-C?

You can check if [string length] == 0 . This will check if it's a valid but empty string (@"") as well as if it's nil, since calling length on nil will also return 0.

Is nil and null the same in C?

Nil is for object pointers, NULL is for non pointers, Null and Nil both defined to be equal to the value zero. NULL is a void *, nil is an id, and Nil is a Class pointer, NULL is used for non-object pointer (like a C pointer) in Objective-C.

Is nil same as?

Nil means the same as zero. It is usually used to say what the score is in sports such as rugby or football. They beat us one-nil in the final. If you say that something is nil, you mean that it does not exist at all.

How do I check if an object is nil in Objective-C?

Any message to nil will return a result which is the equivalent to 0 for the type requested. Since the 0 for a boolean is NO, that is the result. Show activity on this post. Hope it helps.


2 Answers

Just because a variable is set to a value other than nil doesn't mean it's pointing to a valid object. For example:

id object = [[NSObject alloc] init];
[object release];
NSLog(@"%@", object); // Not nil, but a deallocated object,
                      // meaning a likely crash

Your timer has probably already been gotten rid of (or possibly hasn't been created at all?) but the variable wasn't set to nil.

like image 124
Chuck Avatar answered Sep 22 '22 13:09

Chuck


I just ran into a similar issue, so here's another example of what might cause a check such as yours to fail.

In my case, I was getting the value from a dictionary like this:

NSString *text = [dict objectForKey:@"text"];

Later on, I was using the variable like this:

if (text) {
    // do something with "text"
}

This resulted in a EXC_BAD_ACCESS error and program crash.

The problem was that my dictionary used NSNull values in cases where an object had an empty value (it had been deserialized from JSON), since NSDictionary cannot hold nil values. I ended up working around it like this:

NSString *text = [dict objectForKey:@"text"];
if ([[NSNull null] isEqual:text]) {
    text = nil;
}
like image 31
Mirko Froehlich Avatar answered Sep 25 '22 13:09

Mirko Froehlich