我開始學習Objective-C的基礎知識,目前正在閱讀Kochan的(Progamming Objective C)。Objective C繼承和語法
我被困在繼承主題。
我有2個類和1個子類,XYPoint和矩形,正方形(正方形是矩形的子類)。
我有方法可以保留矩形對象的值X和Y座標。
,這裏是我的main.m文件
#import <Foundation/Foundation.h>
#import "Rectangle.h"
#import "Square.h"
#import "XYPoint.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Square *square1 = [[Square alloc]init];
XYPoint *myPoint = [[XYPoint alloc]init];
[myPoint setX:33 andY:33];
[square1 setOrigin:myPoint];
[myPoint setX:25 andY:25];
NSLog(@"square1 origin is %i and %i",[[square1 origin]x],[[square1 origin]y]);
[myPoint setX:125 andY:125];
NSLog(@"square1 origin is %i and %i",[[square1 origin]x],[[square1 origin]y]);
[myPoint setX:25 andY:25];
NSLog(@"square1 origin is %i and %i",[[square1 origin]x],[[square1 origin]y]);
}
return 0;
}
和我Rectangle.m
-(void) setOrigin:(XYPoint *)pt{
if (!origin)
origin = [[XYPoint alloc]init];
origin.x = pt.x;
origin.y = pt.y;
}
-(XYPoint *)origin {
return origin;
}
和XYPoint.m文件從該計劃
- (void) setX:(int)xVal andY: (int) yVal{
x = xVal;
y = yVal;
}
輸出是:
2014-01-23 15:25:36.368 Rectangle1[4356:303] square1 origin is 33 and 33
2014-01-23 15:25:36.370 Rectangle1[4356:303] square1 origin is 33 and 33
2014-01-23 15:25:36.370 Rectangle1[4356:303] square1 origin is 33 and 33
NSLogged 3次。這種保留方法-(void) setOrigin:(XYPoint *)pt;
有助於保留矩形對象上的XY值,甚至通過setX和Y方法重新設置XY值。
,但是當我改變了保留方法爲這樣:
- (空)setOrigin:(的Xypoint *)PT {
if (!origin)
origin = [[XYPoint alloc]init];
origin = pt;
}
NSLogged輸出變成這樣:
2014-01-23 15:29:54.287 Rectangle1[4398:303] square1 origin is 25 and 25
2014-01-23 15:29:54.288 Rectangle1[4398:303] square1 origin is 125 and 125
2014-01-23 15:29:54.289 Rectangle1[4398:303] square1 origin is 25 and 25
什麼這兩者之間的區別是什麼?這兩個具有相同的特徵指向x和y的相同座標嗎?
哦,我現在看到了,所以origin = pt和origin.x = pt.x之間存在巨大差異。雖然origin = pt用於指向地址值,並且origin.x = pt.x用於將pt.x值存儲到origin.x中,但是目的是什麼! (否定)如果(!起源)呢?是否只有一次功能,檢查原點是否存在? – user3213703
是的。當你說'origin = pt; ** pt的**地址**(即myPoint)**被分配給Origin。當你說'origin.x = pt.x'時,這裏分配的值不是地址。 – iamyogish
我也研究過斯蒂芬的書。如果你走得更遠,他已經用整潔的圖表解釋了這一點。 – iamyogish