Amazon.com Widgets Getter that returns a copy of an object
Welcome, Guest. Please login or register.
Did you miss your activation email?
May 19, 2013, 10:46:08 AM
Home Help Search chat Login Register   
News: Read this please.The Great Kangaroo Escape Looking for reviews of the 4th ed on Amazon!   Twitter:  @skochan
                     

+  Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
|-+  Programming in Objective-C, 4th edition
| |-+  Chapter 8
| | |-+  Getter that returns a copy of an object
Pages: [1]   Go Down
Print
Author Topic: Getter that returns a copy of an object  (Read 486 times)
Chuck
Newbie
*
Posts: 4






« on: March 15, 2012, 11:17:29 AM »

Stupid question, and maybe I'm just not thinking this through properly, but on page 168-169, there is mention of writing a getter that returns a copy of an object so that you don't inadvertently modify instance variables of the source object reference. How can this be accomplished?

Is this how?

Code: (Objective-C)
-(XYPoint *) origin
{
  return (XYPoint *) origin;
}
Logged
skochan
Administrator
Hero Member
*****
Posts: 3103







« Reply #1 on: March 15, 2012, 08:35:31 PM »

Code: (Objective-C)
-(XYPoint *) origin
{
     XYPoint *copiedPoint = [[XYPoint alloc] init];

     copiedPoint.x = origin.x;
     copiedPoint.y = origin.y;

     return copiedPoint;
}
Logged
lessisv
Newbie
*
Posts: 1


Email




« Reply #2 on: May 14, 2012, 05:26:27 AM »

Would it be the same if we wrote this??  :

Code: (Objective-C)
-(XYPoint *) origin  

     XYPoint *copiedPoint = [[XYPoint alloc] init]; 
 
     copiedPoint = origin; 
 
     return copiedPoint; 
}

Logged
happyzhb
Administrator
Newbie
*****
Posts: 47


Email




« Reply #3 on: May 14, 2012, 09:30:49 AM »

Nope, the point here is to init a new XYPoint instance, use the setter method to give the same x and y as the origin, then return the new instance.

If you point your new instance to the original origin object, you didn't do copy, you are returning the same source object reference, the 05 line of your code does not create a "copy", it simply make the copiedPoint instance you just init point to the very same object or "origin".

Hope that is clear.
Logged
Pages: [1]   Go Up
Print
Jump to:  



Login with username, password and session length

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents (c) 2009 classroomM.com. All rights reserved.