Dan*_*hez 5 iphone objective-c ipad ios5
我知道如何创建一个协议,但我想知道创建一个代理协议的最佳做法是什么,就像Apple为UIAppearance协议和某些UI类的实现所做的那样.
为什么我想这样做?因为我已经有很多UI类,我想集中实现代码的改变颜色.
也许是一个奇怪的问题,但我的好奇心驱使我到了这一步.
谢谢
Nic*_*ood 11
只需使代理成为静态对象并通过类级方法访问它,就像实现单例一样,例如
@implementation MyClass
+ (MyProxyObject *)proxy
{
static MyProxyObject *sharedProxy = nil;
if (sharedProxy == nil)
{
sharedProxy = [[MyProxyObject alloc] init];
}
return sharedProxy;
}
@end
Run Code Online (Sandbox Code Playgroud)
然后对于你的类的任何属性,例如textColor,只需让你的类使用[[self class] proxy] .textColor中的值,而不是存储它自己的值.例如
@interface MyClass : UIView
@property (nonatomic, strong) textColor
@end
@implementation MyClass
- (UIColor *)textColor
{
return textColor ?: [[self class] proxy].textColor
}
@end
Run Code Online (Sandbox Code Playgroud)
如果您需要在代理上的属性发生更改时立即刷新屏幕视图,则可以通过让代理在其textColor setter方法中广播NSNotification,让所有实例观察该通知并调用setNeedsDisplay来实现.当他们收到它.