【问题标题】:Separate instances of custom class have the same values as each other自定义类的单独实例彼此具有相同的值
【发布时间】:2016-02-09 08:08:44
【问题描述】:

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

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

更新

这是我的颜色类:

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

【问题讨论】:

  • 请显示你的Color类的代码。
  • 为什么要自定义颜色类?
  • @Avi 因为我想保存自定义颜色。
  • init太多了:分别是Color *orange = [[Color alloc] initWithRed:255.0 andGreen:128.0 andBlue:0.0];
  • UIColor 符合 NSCoding。你是怎么存的,这样还不够?

标签: ios objective-c instance-variables


【解决方案1】:

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

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

@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

【讨论】:

    猜你喜欢
    • 2010-11-05
    • 1970-01-01
    • 2021-09-24
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多