Question

A few threads here discuss the new iOS 6 Xcode error that pops up in the console when sending nil dates to Calendar methods:

-[__NSCFCalendar components:fromDate:toDate:options:]: fromDate cannot be nil
I mean really, what do you think that operation is supposed to mean with a nil fromDate?
An exception has been avoided for now.
A few of these errors are going to be reported with this complaint, then further 
violations will simply silently do whatever random thing results from the nil.

The error made me chuckle a bit, but got me to thinking....

The code I've written that results in this error takes date information from a multitude of sources (from date formatters, strings, user input, etc), and I really don't expect every date that is supplied to be valid - I know full well that some will be nil, and I'm quite happy dealing with the results of such objects.

When I first started programming in Objective C one of the features I read up on was sending messages to nil objects. This was great because it meant that I didn't have to worry about passing around nil objects.

Now I've got a grumpy error message from Xcode telling me that I've sent a message to a nil object.

Is the inference now that I've got to check every object is not nil before using it in methods? Am I doing something totally heinous working with nil objects?

Was it helpful?

Solution

Is the inference now that I've got to check every object is not nil before using it in methods?

No, that is not the inference. The inference is that you have to check the date reference you're sending to NSCalendar, because the result of sending it a nil reference is undefined. It might work for you at the moment, but Apple could change the behavior in a future release to do whatever it wants, up to and including clubbing a baby seal. Oh, won't you please think of the baby seals?

Am I doing something totally heinous working with nil objects?

No. It's 100% fine to send a message to a receiver that might be nil, if the result you want back is nil or zero in that case. In this case, you're not sending a message to nil. You're sending a nil argument to a non-nil receiver that wasn't expecting it. In one case, the receiver is nil; in the other case, the argument is nil.

OTHER TIPS

Now I've got a grumpy error message from Xcode telling me that I've sent a message to a nil object.

Incorrect. Your NSCalendar (the receiver) is not nil. What's nil is the NSDate you're passing as one of the arguments to the method. NSCalendar doesn't have any clue what to do when you give it a nil NSDate, so it gives you a log message instead of throwing an exception and crashing your app.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top