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;
}
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;
}
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)
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.
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.