being noob in objective-c,i came across problem in object ownership in class cannot explain reason.
suppose have class called point
describes point x,y. class called rectangle has object of type point
represents left bottom edge. following implementation
@implementation rectangle { point *origin; } -(point *) origin { return origin; } -(void) setorigin: (point *) pt { origin = pt; } @end
now instantiate rectangle, assign origin pointer object of point
rectangle *rectangle2 = [[rectangle alloc] init]; point *pt = [[point alloc] init]; [pt setx:1 andy:2]; rectangle2.origin = pt; nslog(@"point's x= %i, y=%i",pt.x,pt.y); // result: point's x=1,y=2 nslog(@"rectangle's origin x= %i, y=%i",rectangle2.origin.x,rectangle2.origin.y); //rectangle's origin x=1,y=2
now if change x,y of object pt(following line of code), rectangle2 object's origin change well, because not own object, instead points pt pointing to
[pt setx:10 andy:12]; nslog(@"point's x= %i, y=%i",pt.x,pt.y); // result: point's x=10,y=12 nslog(@"rectangle's origin x= %i, y=%i",rectangle2.origin.x,rectangle2.origin.y); //rectangle's origin x=10,y=12
this logical, no issue.
issue seems happening in similar scenario. addresscard class has object of type nsstring,
@implementation addresscard{ nsstring *phone; } -(void) setphone:(nsstring *) p { phone = p; } -(nsstring *) name { return name; } @end
i instantiate addresscard, assign nsstring pointer phone object.
addresscard *addresscard1 = [[addresscard alloc] init]; nsstring *phoneobject = @"(111) 111 - 1111"; addresscard1.phone = phoneobject; nslog(@"addresscard1 phone: %@",addresscard1.phone); // result: (111) 111 - 1111 nslog(@"phone object: %@",phoneobject); // result: (111) 111 - 1111
but if change phoneobject, addresscard1.phone won't change despite way i'm setting phone object in addresscard class (setphone method in class implementation)
phoneobject = [nsstring stringwithstring:@"phone changed"]; nslog(@"%@",phoneobject); //result : phone changed nslog(@"phone after change in addresscard is: %@",addresscard1.phone); // result: (111) 111 - 1111
could objective-c ninja tells me what's difference between 2 snippets, , reason of this?
in first case, modify object: changing x
, y
in point.
in second case, create new string, , point phoneobject
. didn't modify string (and couldn't anyway - nsstring
immutable). means original string gave address card still exists , still valid, address card still uses string. if want use new one, need tell to, putting:
addresscard1.phone = phoneobject;
again after reassigning phoneobject
.
Comments
Post a Comment