6

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

1 Answer 1

12

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.

4
  • Thanks @Nick, that's brilliant!. I'm going to follow your recommendation. Jan 23, 2012 at 20:13
  • Actually it did, but I click it by error. Sorry Nick. Accepted again. Jan 25, 2012 at 11:38
  • This is brilliant, but my question is if there's an option to have a local override. Or does that break the proxy pattern? e.g. myView.textColor = foo doesn't go to the proxy, it sets a local override for the textColor only for that instance.
    – makdad
    Apr 19, 2012 at 6:56
  • 1
    I've updated the answer so it returns the shared value if the local value is nil but otherwise returns the local value instead. Apr 19, 2012 at 18:16

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.