自定义 class 的单独实例彼此具有相同的值

Separate instances of custom class have the same values as each other

我有 4 个颜色为 class 的对象,我是这样初始化的:

Color *orange = [[[Color alloc] init] initWithRed:255.0 andGreen:128.0 andBlue:0.0];
Color *purple = [[[Color alloc] init] initWithRed:255.0 andGreen:0.0 andBlue:127.0];
Color *cyan = [[[Color alloc] init] initWithRed:204.0 andGreen:0.0 andBlue:102.0];
Color *violet = [[[Color alloc] init] initWithRed:127.0 andGreen:0.0 andBlue:255.0];

这些颜色存储在一个数组中:

colors = [NSArray arrayWithObjects:orange, purple, cyan, violet, nil];

稍后我将给按钮设置这样的背景颜色:

button1.backgroundColor = [UIColor colorWithRed: ([([colors objectAtIndex: 0]) getRed]/255.0)
                            green:([([colors objectAtIndex: 0]) getGreen]/255.0)
                            blue:([([colors objectAtIndex: 0]) getBlue]/255.9) alpha:1];

我现在的问题是,即使索引 0 处的颜色是橙色,按钮的颜色也是紫色。如果我从数组中删除紫罗兰色,则没有任何变化,但是当我删除颜色紫罗兰色时,按钮变为青色。

是什么导致了这种奇怪的行为?还是我做错了什么?

更新

这是我的颜色class:

double Red;
double Green;
double Blue;


- (id)initWithRed:(double) red andGreen:(double) green andBlue:(double) blue {
    self = [super init];
    if (self)
    {
        [self setRed:red];
        [self setGreen:green];
        [self setBlue:blue];

    }
    return self;
}



- (void) setRed:(double) red {
    Red = red;
}

- (void) setGreen:(double) green {
    Green = green;
}

- (void) setBlue:(double) blue {
    Blue = blue;
}

- (double) getRed {
    return Red;
}

- (double) getGreen {
    return Green;
}

- (double) getBlue {
    return Blue;
}

您打算成为实例变量的三个变量已在最外层声明,全局变量也是如此,即它们由每个实例共享。因此,无论您使用哪个实例,您获得的颜色都是您最后创建的颜色。

要声明实例变量,请将它们放在 class:

开头的大括号中
@implementation Color : NSObject
{
    double red;
    double green;
    double blue;
}

// methods...

@end

您还为每个对象调用了两个 init 方法,只调用一个,例如:

Color *cyan = [[Color alloc] initWithRed:204.0 andGreen:0.0 andBlue:102.0];

HTH