Use of a singleton for creating a basic style helper class

筅森魡賤 提交于 2019-12-06 09:32:31

问题


I am a newbie to objective-c and I have an architectural or design pattern question. I am building an ios app and like most ios apps, it uses various colors, font, patterns etc. Perhaps I am currently writing code incorrectly but I find myself rewriting things like color settings. And as a result, changing colors becomes an exercise in finding all of the color settings in the code, rewriting them, etc. Seems a bit inefficient to me.

For example, I use a dark red color in multiple places in my app. I tend to write the [UIColor colorWithRed...] method rather frequently. However, I curious if creating a singleton that returns my custom colors (as a UIColor) is a reasonable approach to "modularizing my style package." Thus I could write something like this

[label setTextColor:[[MyStyleSingletonClass sharedStyler] myDarkRed]];

Thus, if the designers suddenly want myDarkRed to be a touch darker, I change it once and it is good to go across the app. Clearly there is more to style and UX than color, but I am curious if this approach makes sense or if I am setting myself up for issues in the future. Or maybe this capability exists in objective-c already and I am missing the point. Thanks in advance.


回答1:


I think a better approach to something like this is a category of class methods on UIColor itself. I often write categories of colors for projects with lots of custom colors.

Something like this:

// UIColor+AppAdditions.h
@interface UIColor (AppAdditions)

+ (UIColor *)myDarkRed;

@end

// UIColor+AppAdditions.m

#import "UIColor+AppAdditions.h"

@implementation UIColor (AppAdditions)

+ (UIColor *)myDarkRed
{
    return [UIColor colorWithRed:0.1 green:0.0 blue:0.0 alpha:1.0];
}

@end

That way you don't need a whole Singleton and its more portable incase the Singleton does other things. And you can cleanly access your colors like this:

[label setTextColor:[UIColor myDarkRed]];

Note

As mentioned by Rob and Paul. It is best to name them appropriately. I took the name you had but it would be best to name them specifically for their use and follow conventions such as prefixing and suffixing.




回答2:


Why not use macro?

in YourHelperClass.h

#define DARK_RED    [UIColor colorWithRed:0.1 green:0.0 blue:0.0 alpha:1.0]

and you can use like this(do not forget import YourHelperClass.h) :

[label setTextColor:DARK_RED];

I think it is better use macro



来源:https://stackoverflow.com/questions/15434975/use-of-a-singleton-for-creating-a-basic-style-helper-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!