Message anatomy

A message send is always surrounded by square brackets, and it always has at least two parts:

  • a pointer to the object that is receiving the message

  • the name of the method to be triggered

A message send (like a function call) can also have arguments. Let’s look at an example.

NSDate objects represent a particular date and time. An instance of NSDate can tell you the difference (in seconds) between the date/time it represents and 12:00AM (GMT) on Jan 1, 1970. Ask yours this question by sending the message timeIntervalSince1970 to the NSDate object 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​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​)​;​

 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

Now say you want a new date object – one that is 100,000 seconds later from the one you already have.

The NSDate class has a method called dateByAddingTimeInterval:. You can send this message to the original date object to get the new date object. This method takes an argument: the number of seconds to add. Use it to create a new date object in your main() function:

#​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​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​;​
}​

In the message send [now dateByAddingTimeInterval:100000],

  • now is a pointer to the object that is receiving the message (also known as the receiver)

  • dateByAddingTimeInterval: is the method name (also known as the selector)

  • 100000 is the only argument

Figure 12.2  A message send

A message send
..................Content has been hidden....................

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