14
More Messages

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.

A message with an argument

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.

Figure 14.1  A message send with an argument

A message send with an argument

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:

#​i​m​p​o​r​t​ ​<​F​o​u​n​d​a​t​i​o​n​/​F​o​u​n​d​a​t​i​o​n​.​h​>​

i​n​t​ ​m​a​i​n​ ​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​@​a​u​t​o​r​e​l​e​a​s​e​p​o​o​l​ ​{​

 ​ ​ ​ ​ ​ ​ ​ ​N​S​D​a​t​e​ ​*​n​o​w​ ​=​ ​[​N​S​D​a​t​e​ ​d​a​t​e​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​T​h​i​s​ ​N​S​D​a​t​e​ ​o​b​j​e​c​t​ ​l​i​v​e​s​ ​a​t​ ​%​p​"​,​ ​n​o​w​)​;​
 ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​T​h​e​ ​d​a​t​e​ ​i​s​ ​%​@​"​,​ ​n​o​w​)​;​

 ​ ​ ​ ​ ​ ​ ​ ​d​o​u​b​l​e​ ​s​e​c​o​n​d​s​ ​=​ ​[​n​o​w​ ​t​i​m​e​I​n​t​e​r​v​a​l​S​i​n​c​e​1​9​7​0​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​I​t​ ​h​a​s​ ​b​e​e​n​ ​%​f​ ​s​e​c​o​n​d​s​ ​s​i​n​c​e​ ​t​h​e​ ​s​t​a​r​t​ ​o​f​ ​1​9​7​0​.​"​,​ ​s​e​c​o​n​d​s​)​;​

 ​ ​ ​ ​ ​ ​ ​ ​N​S​D​a​t​e​ ​*​l​a​t​e​r​ ​=​ ​[​n​o​w​ ​d​a​t​e​B​y​A​d​d​i​n​g​T​i​m​e​I​n​t​e​r​v​a​l​:​1​0​0​0​0​0​]​;​
 ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​I​n​ ​1​0​0​,​0​0​0​ ​s​e​c​o​n​d​s​ ​i​t​ ​w​i​l​l​ ​b​e​ ​%​@​"​,​ ​l​a​t​e​r​)​;​

 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​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:.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset