0

i am learning Objective C . here i come up with a question that is not understand by me please give a solution to this.

XYPoint.h file

//header file
@interface XYPoint:NSObject
{
int x;
int y;
}

@property int x,y;

-(void) setX:(int ) d_x setY:(int )d_y;

// implementation file XYPoint.m
@synthesize x,y; 
-(void) setX:(int ) d_x setY:(int ) d_y
{
 x=d_x;
 y=d_y;
} 

//Rectangle.h file
@class XYPoint;
@Interface Rectangle:NSObject
{
 int width,height;
 XYPoint *origin;
}

@property int width,height;
-(XYPoint *)origin;
-(void) setOrigin:(XYPoint*)pt;

//at implementation Rectangle.m file
@synthesize width,height;

-(XYPoint *)origin
{
 return origin;
}

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


//in main
#import "Rectangle.h"
#import "XYPoint.h"

int main(int argc,char *argv[])
{
Rectangle *rect=[[Rectangle alloc] init];
XYPoint *my_pt=[[XYPoint alloc] init];

[my_pt setX:50 setY:50];
rect.origin=my_pt;  // how is this possible
return 0;
}

in objective c we can access the instance variable using dot operator if we declare as property . but here origin declared as instance variable in Rectangle class. in main class we access the origin variable using dot . i dont know how it works . and rect.origin=my_pt line calls the setOrigin method how that line call setOrgin method. please explain me

1 Answer 1

2

You slightly misunderstand the Objective-C property system.

a=obj.property;

is strictly equivalent to the call

a=[obj property];

and

obj.property=a;

is strictly equivalent to the call

[obj setProperty:a];

You should think of @property NSObject*foo declarations as the declaration of a pair of methods foo and setFoo:, together with the specification of the retain/release semantics. @synthesize foo is then the implementation of foo and setFoo:. There's nothing more than that.

Sign up to request clarification or add additional context in comments.

2 Comments

you said ob.property=a is strictly equivalent to [obj setProperty:a]; so we need to define setProperty method explicitly or not when we declared property and synthesize for a instance varialbe.
@synthesize property; will generate the two methods property and setProperty: for you, if you didn't already implement them (or one of them) yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.