I was trying something out as I was learning about @property and @synthesize. I thought @property created the instance variables and @synthesize created the getter and setter methods for it.
#import <Foundation/Foundation.h>
@interface XYPoint : NSObject
@property int x, y;
-(void) setX: (int) xVar andY: (int) yVar;
@end
I didn’t synthesize x and y in my implementation file, but I was wondering why I was allowed to do both:
-(void) setX:(int)x {
x = x;
}
-(void) setY:(int)y {
y = y;
}
but got an error message about undeclared identifiers x and y when I did this:
-(void) setX:(int)xVar andY:(int)yVar {
x = xVar;
y = yVar;
}
Also, why didn’t -(void) setY:(int)y and -(void) setX:(int)x have to be declared in the interface file?
This is not quite correct. The
@propertydeclaration basically just makes a promise to other classes: “You can ask me for anintnamedx, and I will also respond to attempts to give me anintto store under that name.” The declaration itself doesn’t create anything in the class, either methods or an ivar.It’s
@synthesizethat does both those things. You can implement your own setter, getter, and ivar yourself, or you can synthesize them (or any combination).So the reason that you’re getting that error when you don’t use
@synthesizeis that no ivars have been created, soxandyaren’t names you can use inside the class.In the first case, you’re not doing what you seem to think you’re doing. In this method:
xis the name of the parameter, and you’re just assigning it to itself. (You can’t have two variables with the same name in the same scope. If you had created an ivar namedx, you’d get a compiler warning about the method parameter shadowing the ivar. That means that the parameter name, being the same as the ivar, won’t allow you to access the ivar.)If you change that to:
you’ll see the same error about
xbeing undeclared.They are declared by the
@propertydirective.