Srini
Srini

Reputation: 387

Set an instance variable of an object from another object

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

Upvotes: 0

Views: 228

Answers (1)

Yuji
Yuji

Reputation: 34185

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.

Upvotes: 2

Related Questions