Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a proxy protocol like UIAppearance

I know how to create a protocol already but I'm wondering what would be the best practice to create a proxy protocol like Apple did for the UIAppearance protocol and the implementation on certain UI classes.

Why I want to do it this way? Because I already have a lot of UI classes and I would like to centralize the implementation of the code for changing color.

Maybe an odd question but my curiosity drove me to this point.

Thanks

like image 990
Daniel Sanchez Avatar asked Jan 23 '12 14:01

Daniel Sanchez


1 Answers

Just make the proxy a static object and access it through class-level methods, the same way you'd implement a singleton, e.g.

@implementation MyClass

+ (MyProxyObject *)proxy
{
    static MyProxyObject *sharedProxy = nil;
    if (sharedProxy == nil)
    {
        sharedProxy = [[MyProxyObject alloc] init];
    }
    return sharedProxy;
}

@end

Then for any property of your class, e.g. textColor, just have your class use the value in [[self class] proxy].textColor instead of storing its own value. E.g.

@interface MyClass : UIView

@property (nonatomic, strong) textColor

@end

@implementation MyClass

- (UIColor *)textColor
{
    return textColor ?: [[self class] proxy].textColor
}

@end

If you need a way to refresh your onscreen views immediately whenever a property on the proxy is changed, you could do that by having the proxy broadcast an NSNotification in its textColor setter method, and have all the instances observe that notification and call setNeedsDisplay on themselves when they receive it.

like image 91
Nick Lockwood Avatar answered Sep 18 '22 11:09

Nick Lockwood