Nesting message sends

Message sends can be nested. For instance, to find out the number of seconds since the start of 1970, you could write your code this way:

 ​ ​ ​ ​N​S​D​a​t​e​ ​*​n​o​w​ ​=​ ​[​N​S​D​a​t​e​ ​d​a​t​e​]​;​
 ​ ​ ​ ​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​)​;​

Or you could nest the two message sends like this:

 ​ ​ ​ ​d​o​u​b​l​e​ ​s​e​c​o​n​d​s​ ​=​ ​[​[​N​S​D​a​t​e​ ​d​a​t​e​]​ ​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​)​;​

When message sends are nested, the system will handle the message send on the inside first and then the message that contains it. So date is sent to the NSDate class, and the result of that (a pointer to the newly-created instance) is sent timeIntervalSince1970.

You will often see nested message sends in code, and you need to know how to read them. However, when writing your own code, you may find that nesting messages is counterproductive. It makes your code harder to read and harder to debug because more than one thing is happening on one line.

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

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