我正在努力确保我在使用Objective-C时正确处理问题,如果可能的话,我会提出两个快速问题:
(1)我是否正在从Rectangle中正确访问Position对象?我是否可以通过我在init中设置的指针访问其中包含的Position对象,还是有更好的方法?
(2)在[setPosX:andPosY:]设置Position实例变量的两种方法中哪一种最好,或者它真的无关紧要?
// INTERFACE
@interface Position: NSObject {
int posX;
int posY;
}
@property(assign) int posX;
@property(assign) int posY;
@end
@interface Rectangle : NSObject {
Position *coord;
}
-(void) setPosX:(int) inPosX andPosY:(int) inPosY;
// IMPLEMENTATION
@implementation Rectangle
-(id) init {
self = [super init];
if (self) {
NSLog(@"_init: %@", self);
coord = [[Position alloc] init];
// Released in dealloc (not shown)
}
return(self);
}
-(void) setPosX:(int) inPosX andPosY:(int) inPosY {
//[coord setPosX:inPosX];
//[coord setPosY:inPosY];
coord.posX = inPosX;
coord.posY = inPosY;
}
然后我在初始化时调用 - (id)initWithX:andY:来自Rectangle对象吗?如果是这样,我如何从main()中设置posX和posY?或者我用另一个 - (id)initWithX:andY:替换矩形的init并传递值?
@implementation Rectangle
-(id) init {
self = [super init];
if (self) {
NSLog(@"_init: %@", self);
coord = [[Position alloc] initWithX:1234 andY:5678];
}
return(self);
}
...
欢呼加里
答案 0 :(得分:2)
(1)您正确访问它。
(2)在objective-c 2.0中,赋值具有相同的效果。
设计明智,你想做:
-(void) setPosX:(int) inPosX andPosY:(int) inPosY;
...成为一种位置方法。这将数据和与之相关的方法封装到一个对象中。所以你可以打电话:
coord = [[Position alloc] initWithX:inPosX andY:inPosY];
或 [coord setPosX:inPosX andPosY:inPOSY];
更清洁,更易于维护。
编辑O1
然后我调用 - (id)initWithX:andY: 我初始化时从Rectangle对象 它?
这取决于你的设计。如果coord
属性对Rectangle
实例至关重要,则应在初始化Rectangle
实例时调用它。您甚至可以为Rectangle
编写一个初始值设定项,它将位置或x和y作为输入。例如:
-(id) initWithPosition:(Position *) aPos {
self = [super init];
if (self) {
NSLog(@"_init: %@", self);
coord = aPos;
// Released in dealloc (not shown)
}
return self;
}
您还应该为Position类编写一个connivence初始值设定项:
-(id) initWithX:(NSInteger) x andY:(NSInteger) y{
self=[super init];
self.posX=x;
self.posY=y;
return self;
}
然后你会打电话给:
Position *aPos=[[Position alloc] initWithX:100 andY:50];
Rectangle *aRec=[[Rectangle alloc] initWithPosition:aPos];
或者您可以为Rectangle编写另一个组合初始值设定项:
-(id) initWithXCoordinate:(NSInteger) x andYCoordinate:(NSInteger) y{
self=[super init];
Position *aPos=[[Position alloc] initWithX:x andY:y];
self.coord=aPos;
return self;
}
并称之为:
Rectangle *aRec=[[Rectangle alloc] initWithXCoordinate:100
andYCoordinate:50];
这些都是粗略的例子,但你明白了。 Objective-c为您设置初始化程序提供了很大的灵活性,因此您可以创建任何方便的初始化程序。
您通常希望避免使用实际函数而不是类中的方法。
答案 1 :(得分:1)
(1)您还需要在-dealloc
中发布它。创建一个具有未初始化位置的Rectangle真的有意义吗?换句话说,[[Position alloc] init]
的行为是什么,并且Rectangle在该状态下应该具有位置是否合理?
(2)他们都做同样的事情。你写的那个比你注释的那个更清晰,因为它表明你正在改变属性而不是让对象做某事。无论如何,这是我的意见。有些人同意,有些人不同意,而且我说的行为是一样的。