13
More Messages

In the last chapter, you sent a few messages. Let’s look again at the lines where you sent those messages and triggered the corresponding methods:

N​S​D​a​t​e​ ​*​n​o​w​ ​=​ ​[​N​S​D​a​t​e​ ​d​a​t​e​]​;​

We say that the date method is a class method. That is, you cause the method to execute by sending a message to the NSDate class. The date method returns a pointer to an instance of NSDate.

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​]​;​

We say that timeIntervalSince1970 is an instance method. You cause the method to execute by sending a message to an instance of the class. The timeIntervalSince1970 method returns a double.

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​]​;​

dateByAddingTimeInterval: is another instance method. This method takes one argument. You can determine this by the colon in the method name. This method also returns a pointer to an instance of NSDate.

Nesting message sends

There is a class method alloc that returns a pointer to a new object that needs to be initialized. That pointer is then used to send the new object the message init. Using alloc and init is the most common way to create objects in Objective-C. It is good practice (and the only Apple-approved way) to send both of these messages in one line of code by nesting the message sends:

[​[​N​S​D​a​t​e​ ​a​l​l​o​c​]​ ​i​n​i​t​]​;​

The system will execute the messages on the inside first and then the messages that contain them. So, alloc is sent to the NSDate class, and the result of that (a pointer to the newly-created instance) is then sent init.

init returns a pointer to the new object (which is nearly always the pointer that came out of the alloc method), so we can use what’s returned from init for the assignment. Try out these nested messages in your code by changing the line:

N​S​D​a​t​e​ ​*​n​o​w​ ​=​ ​[​N​S​D​a​t​e​ ​d​a​t​e​]​;​

to

N​S​D​a​t​e​ ​*​n​o​w​ ​=​ ​[​[​N​S​D​a​t​e​ ​a​l​l​o​c​]​ ​i​n​i​t​]​;​
..................Content has been hidden....................

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