-4

These methods are inside a class called Rectangle, this is a part of the implementation file Rectangle.m

#import "XYPoint.h"

- (void)setOrigin:(XYPoint *)pt {
    origin = pt;
}

- (XYPoint *)origin {
    return origin;
}
icodebuster
  • 8,890
  • 7
  • 62
  • 65
boodo17
  • 15
  • 3

1 Answers1

3

Not much special to Objective-C about it. It's just the setter and getter for a property called origin.

When you set a new origin using either

self.origin = /*some new value*/;

or

[self setOrigin: /*some new value*/];

the first method is going to be called.

In the same way the other method is called when you get value using either self.origin or [self origin] (but for the second method)


Naming convention

You usually call these methods "setters and getters" or simply "accessors". In other languages, like Java, it is common to name these methods setXyz and getXyz but Objective-C names them setXyz and xyz for the getter.

Properties vs. Instance variables

These days you seldom have to write these methods yourself. You get the same benefits by using a property and letting the compiler generate this boilerplate code for you. The property in your example would look something like this and replace all that code:

@property (weak) XYPoint *origin; // weak since your methods are not retaining the new value

You can read about the reason to use properties vs instance variables in this answer. In short: having a method wrap the variable enables you to have memory management (like copying or retaining) of objects and makes it possible to call other methods enabling KVC/KVO but it has a slight overhead to it.

Community
  • 1
  • 1
David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205
  • 1
    I understand that they are a setter and a getter but why are they not in this format? -(void) setOrigin: (int) n { origin = n; } -(int) origin { return origin; } – boodo17 May 26 '13 at 09:03
  • Do you mean `int` instead of `XYPoint *`? – David Rönnqvist May 26 '13 at 09:06
  • yes, I mean why is it in the -(XYPoint *) and not in the -(int) format? we could simply use -(void) setOrigin : (int) n as a setter and -(int) origin as a getter. – boodo17 May 26 '13 at 09:11
  • An integer is only one number so it would only be able to represent either the x _or_ y coordinate of the point (or z if you are in 3D). The point is an object which I assume has an x and a y property in turn. So the rectangle class probably have both a point (x, y) and a size (width, height). – David Rönnqvist May 26 '13 at 09:13
  • You have imported XYPoint in your header. I think this is an example teaching you to add a XYPoint class as an instance in your Rectangle Class. And it's demonstrating how the getter and setter for XYPoint instance. – John May 26 '13 at 10:26