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

时间:2015-11-08 16:36:12

标签: ios objective-c instance-variables

我有我的Color类的4个对象,我初始化如下:

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处的颜色为橙色,按钮的颜色也是紫色。如果我从阵列中移除紫罗兰没有任何变化,但是当我移除颜色紫色时,按钮变为青色。

导致这种奇怪行为的原因是什么?或者我做错了什么?

更新

这是我的Color类:

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;
}

1 个答案:

答案 0 :(得分:1)

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

要声明实例变量,请将它们放在类开头的大括号中:

@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