1

尝试运行以下代码(片段)时,我遇到了错误(在主题中说明)。错误指向我下面代码的第 3 行和第 4 行。

id shape[3];  
shape[0] = [[Circle alloc]init];  
shape[0].fillColor = kRed;  
shape[0].shapeBounds = bound0;  

在这组代码之前,我已经为 ShapeColor 和 ShapeBoundary 定义了枚举和结构,如下所示

typedef enum
{
kRed,
kBlue,
kGreen,
kPurple
}ShapeColor;

typedef struct
{
int x;
int y;
int width;
int height;
}ShapeBoundary;  

另外,我已经定义了“Circle”类的接口和实现

@interface Circle : NSObject  
{  
ShapeColor fillColor;  
ShapeBoundary shapeBounds;  
}  

@property ShapeColor fillColor;  
@property ShapeBoundary shapeBounds;  

@end  

@implementation Circle  

@synthesize fillColor;  
@synthesize shapeBounds;  

@end

我使用@property 和@synthesize 为“fillColor”和“Shapebounds”定义了我的getter 和setter 方法。我使用属性和综合的方式是否有问题导致主题出现错误?或者我有什么问题错过了。非常感谢您对此提出任何建议。

谢谢并恭祝安康

振和

4

1 回答 1

2

为了对属性使用点表示法,变量的类必须是静态类型的或强制类型转换的。也就是说,您的代码必须声明对象的类而不是使用 id。如果你使用Circle *shape[3];, 否则((Circle*)shape[0]).fillColor你的错误就会消失。当您希望您的变量被动态类型化(使用id)时,您需要使用等效的方法来获取属性:

id shape[3];
shape[0] = [[Circle alloc] init];
[shape[0] setFillColor:kRed];
[shape[0] setShapeBounds:bound0];

还要确保在执行此操作的文件中包含 Circle 类的标题。

于 2011-04-04T02:50:54.003 回答