I’m a beginner and I wrote this code:
#import <Foundation/Foundation.h>
@interface XYPoint : NSObject {
int pointX;
int pointY;
}
- (void) print;
- (void) setX: (int) x;
- (void) setY: (int) y;
@end
@implementation XYPoint
-(void) print {
NSLog(@"X is %i and Y is %i", pointX, pointY);
}
-(void) setX: (int) x {
pointX = x;
}
-(void) setY: (int) y {
pointY = y;
}
@end
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
XYPoint *myCord = [[XYPoint alloc] init];
[myCord setX: 4];
[myCord setY: 6];
[myCord print];
[myCord release];
[pool drain];
return 0;
}
What I need help with is I cannot for the life of me understand the relationship between “pointX” and setX and “x”
PointXis called an instance variable – this is what would be called in most other languages a private class-level variable. It represents a piece of information that your class needs to store internally, and by default is not exposed to other objects in the system.setXis a method that you explicitly create, that allows other objects to assign a value to the privatePointXinstance variable.xis the parameter that the external calling object passes to thesetXmethod.Note that the most common way of exposing access to a private instance variable is through the use of defined properties. In your case, you would add something like this in your interface:
and then this in your implementation:
This syntax allows you to (effectively) directly access the
PointXinstance variable, by automagically creating a wrapper property (with matching -get and -set methods) with the same name.