我在尝试运行以下代码(片段)时遇到了错误(在主题中说明)。错误指向我下面代码的第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方法。我使用属性和合成的方式是否有问题导致主题中的错误?或者是否存在我错过的任何事情。非常感谢任何有关此事的建议。
谢谢和问候
Zhen Hoe
答案 0 :(得分:3)
为了对属性使用点表示法,必须对变量的类进行静态类型化或强制转换。也就是说,您的代码必须声明对象的类而不是使用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类的标题。