Search code examples
objective-cxcodensdate

Is it safe to assign NULL to an NSDate*?


I'm writing a game that includes a Quest class, which has a completionDate property of type NSDate *, which records the date and time that the player completed the quest. It's declaration (in Quest.h) is:

@property (nonatomic) NSDate *completionDate;

I figured it would be reasonable, in a case where the player had not yet completed a quest, to assign the quest's completionDate property a value of NULL to indicate this. However, when I do:

quest.completionDate = NULL;

XCode (11.1) gives a warning on that line of code: Null passed to a callee that requires a non-null argument.

Despite the warning, my code seems to work as intended: Doing a check like the following to determine whether or not the quest has been completed seems to work fine:

if (quest.completionDate == NULL) { ... }

Researching this, I found similar questions like Xcode 7, Obj-C, "Null passed to a callee that requires a non-null argument", with answers suggesting just using the init method to initialize an object to a default state. However, in the case of NSDate, init initializes the date to "now" (the current date/time), so that won't work for what I'm trying to do.

My question: Is there any reason not to assign NULL to an NSDate *?


Solution

  • Add the nullable property attribute to your completionDate.

    @property (nonatomic, nullable) NSDate *completionDate;
    

    To learn more about declaring nullable types, see this Apple blog post Nullability and Objective-C.