Objects are very chatty by nature. They send and receive lots of messages about the work they are doing. In this chapter, you will learn about messages with arguments, nested message sends, and more.
The TimeAfterTime program has an NSDate initialized to the date and time at which it is created. What if you want to represent a date in the future – say, 100,000 seconds from the first date? You can create such a date by sending the dateByAddingTimeInterval: message to the original instance of NSDate.
Notice the colon at the end of the dateByAddingTimeInterval: method’s name. This tells you that dateByAddingTimeInterval: accepts an argument. Methods, like functions, can have zero, one, or more arguments.
The dateByAddingTimeInterval: method accepts the number of seconds by which the new NSDate should differ from the original one. (A negative number would give you an NSDate in the past.)
In TimeAfterTime, use dateByAddingTimeInterval: to create a second date that is 100,000 seconds (a bit over a day) later than the date pointed to by now:
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { @autoreleasepool { NSDate *now = [NSDate date]; NSLog(@"This NSDate object lives at %p", now); NSLog(@"The date is %@", now); double seconds = [now timeIntervalSince1970]; NSLog(@"It has been %f seconds since the start of 1970.", seconds); NSDate *later = [now dateByAddingTimeInterval:100000]; NSLog(@"In 100,000 seconds it will be %@", later); } return 0; }
When a method has an argument, the colon is an essential part of the method’s name. There is no method named dateByAddingTimeInterval. There is only dateByAddingTimeInterval:.