創建後的對象除了釋放它並創建一個新對象(您可以在init方法中執行,實際上經常爲單例或類集羣完成)之外,您無法更改該對象,但是並不是你真正想要的。
給一個現有的Shape對象,有一些屬性,你唯一真正的選擇是根據形狀屬性創建一個新的對象。喜歡的東西:
在Shape.m:
- (id) initWithShape:(Shape*)aShape {
self = [super init];
if (self != nil) {
// copy general properties
_x = aShape.x;
_y = aShape.y;
_color = [aShape.color copy];
}
return self;
}
在Circle.m:
- (id) initWithShape:(Shape*)aShape {
self = [super initWithShale:aShape];
if (self != nil) {
// base properties on the class of the shape
if ([aShape isKindOfClass:[Oval class]]) {
// average the short and long diameter to a radius
_radius = ([(Oval*)aShape shortDiameter] + [(Oval*)aShape longDiameter])/4;
} else {
// or use generic Shape methods
_radius = aShape.size/2;
}
}
return self;
}
謝謝。這是我正在尋找的。在Shape.m中放入一個initWithShape使得在查看Circle.m時代碼清晰 – 2009-06-30 04:04:44