与指针和对象混淆(Objective-C) [英] Confusion with pointers and objects (Objective-C)
问题描述
作者写道,每当point
的值改变myRect's origin
的值也会改变,但我不明白如何转origin
到一个对象修复它.创建对象和创建指针有什么区别?
The author wrote that whenever the value of point
changes the value of myRect's origin
will change as well, but I don't understand how turning origin
into an object fixes it. What's the difference between creating an object and a pointer?
修正setOrigin
方法:
-(void) setOrigin:(XYpoint *)pt {
if (! origin)
origin = [[XYpoint alloc] init];
origin.x = pt.x;
origin.y = pt.y;
}
<小时>
#import <Foundation/Foundation.h>
@interface XYPoint : NSObject
@property int x, y;
@end
<小时>
#import "XYpoint.h"
@implementation XYPoint
@synthesize x, y;
@end
<小时>
#import <Foundation/Foundation.h>
@class XYPoint;
@interface Rectangle: NSObject
-(void) setOrigin: (XYPoint *) pt;
@end
<小时>
#import "Rectangle.h"
#import "XYpoint.h"
@implementation Rectangle {
XYPoint *origin;
}
-(void) setOrigin:(XYPoint *)pt {
origin = pt;
}
@end
<小时>
#import "XYpoint.h"
#import "Rectangle.h"
int main (int argc, char *argv[]) {
@autoreleasepool {
Rectangle *myRect = [[Rectangle alloc] init];
XYpoint *point = [[XYpoint alloc] init];
point.x = 3;
point.y = 8;
[myRect setOrigin: point];
}
return 0;
}
推荐答案
XYPoint *origin;
是指向包含 x
和 y<的对象的指针/代码>.特别是在这种情况下,您有两个指向同一个对象的引用.
myRect.origin
和 point
指向同一个 XYpoint
对象.这意味着如果您通过任一方式更改 x
或 y
的值(myRect.origin.x = 1
或 point.x = 1
),更新后的 x
和 y
将在任何一种方式(myRect.origin
或 点
).
XYPoint *origin;
is a pointer to the object that contains x
and y
. In this case in particular you have two references that point to the same exact object. myRect.origin
and point
point to the same XYpoint
object. What this means is if you change the value of x
or y
by either means (myRect.origin.x = 1
or point.x = 1
), the updated x
and y
will be when accessed either way (myRect.origin
or point
).
这篇关于与指针和对象混淆(Objective-C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!