我希望能够只用一个对象设置很多属性。例如,让我说我有一堆UIButton
,我想改变他们的背景颜色。
我希望能够做到这样的事情:
UIColor *startColor= [UIColor blackColor];
btnA.backgroundColor = startColor;
btnB.backgroundColor = startColor;
btnC.backgroundColor = startColor;
然后在某处使用另一种方法:
startColor = [UIColor greenColor];
这会将所有按钮背景更改为绿色。
我知道setBackgroundColor:
方法会复制UIColor
,因此以这种方式更改它是不可能的。
怎么会这样做呢?你需要某种(双)指针。你需要实现自己的课程吗?或者这已经有办法做到这一点?我应该提一下,我来自C ++背景。
答案 0 :(得分:2)
在这种特定情况下,您尝试做的事情是不可能的,因为UIColor
对象是不可变的。
Objective-C允许您以与C和C ++共享对象相同的方式共享对象 - 通过指针。当多个对象引用可变对象并且对象发生更改时,所有引用对象都可以立即看到此更改。不可变对象不能改变,因此改变某些对象“看到”的唯一方法是设置替换对象(即新颜色)。
另一方面,可变对象允许您不断更改外部对象,并使更改在其中自动变为“可见”。考虑这个例子:
@interface Demo
// Note: NSString properties are often marked as "copy" in production code
// in order to avoid the behavior that this code demonstrates.
@property (nonatomic, readonly) NSString *name;
-(void)show;
@end
@implementation Demo
-(void)show {
NSLog(@"%@", _name);
}
@end
...
Demo *one = [[Demo alloc] init];
Demo *two = [[Demo alloc] init];
Demo *three = [[Demo alloc] init];
NSMutableString *commonName = [NSMutableString stringWithString:@"hello"];
pne.name = two.name = three.name = commonName;
// Now the name is shared
[one show];
[two show];
[three show];
[commonName appendFormat:@", world!"];
[one show];
[two show];
[three show];
前三次拨打show
会产生三个hello
;最后三次调用产生三个hello, world!
s。