tech_human
tech_human

Reputation: 7100

Setting today's date to NSDate

I have a NSDate property as below and I wish to set it with today's date.

@property (nonatomic, copy, readwrite) NSDate *todayDate;

I tried the following but I am getting an error:

NSDate *date = [[NSDate alloc] init];
self.todayDate = [date isToday];

I guess, isToday just checks whether the date is today's date and doesn't set the date.

I am getting following 2 errors:

Implicit conversion of 'BOOL' (aka 'signed char') to 'NSDate *' is disallowed with ARC
Incompatible integer to pointer conversion assigning to 'NSDate *' from 'BOOL' (aka 'signed char'); 

How do I set NSDate to today's date in Objective C?

Upvotes: 1

Views: 1679

Answers (2)

Chris Trahey
Chris Trahey

Reputation: 18290

NSDate has you covered:

NSDate *today = [NSDate date];

This is a common pattern in Apple's frameworks: semantic "factory" class methods. This call replaces your calls to alloc and init, and is a preferred way to work with common objects. It's also a nice pattern to emulate in your own classes :-)

On of the core concepts which should shed light on the "why" is that of immutability. Many objects (NSString, NSNumber, etc) are considered (at least in practice) to be immutable. This means they get their value exactly once: during init. This leads the the "other" answer also being an instantiation-time technique: a custom initializer.

NSDate *today = [[NSDate alloc] initWithTimeIntervalSinceNow: 0];

Upvotes: 4

Bergasms
Bergasms

Reputation: 2203

This will set your property to todays date. The error is because, as you suspect, you are assigning a boolean to a pointer.

self.todayDate = [NSDate date];

Upvotes: 0

Related Questions