开始寻找全局静态,在一个地方设置颜色,以便在整个应用中使用。我无法理解关于单身人士在SO上的一些非常好的答案(较旧),所以我创建了一个非常简单的处理它的类。根据一些(其他线程),我决定避免使用app委托。
似乎有几种方法可以解决这个问题。作为一个低经验的ios / objective-c开发人员,下面的方法错过了什么? (顺便说一句,它很有效,看起来很简单。)
// Global.h
@interface Global : NSObject
@property (strong, nonatomic) UIColor *myColor;
- (id)initWithColor:(NSString *)color;
// Global.m
@implementation Global
@synthesize myColor;
- (id)initWithColor:(NSString *)color
{
if (!self) {
self = [super init];
}
if ([color isEqualToString:@"greenbackground"])
myColor = [[UIColor alloc] initWithRed:0.0 / 255 green:204.0 / 255 blue:51.0 / 204 alpha:1.0];
... and so on with other colors
return self;
}
@end
稍后使用颜色:
cell.backgroundColor = [[[Global alloc] initWithColor:@"greenbackground"] myColor];
编辑以获得更好的解决方案:
// Global.h
#import <foundation/Foundation.h>
@interface Global : NSObject {
UIColor *myGreen;
UIColor *myRed;
}
@property (nonatomic, retain) UIColor *myGreen;
@property (nonatomic, retain) UIColor *myRed;
+ (id)sharedGlobal;
@end
// Global.m
#import "Global.h"
static Global *sharedMyGlobal = nil;
@implementation Global
@synthesize myGreen;
@synthesize myRed;
#pragma mark Singleton Methods
+ (id)sharedGlobal {
@synchronized(self) {
if (sharedMyGlobal == nil)
sharedMyGlobal = [[self alloc] init];
}
return sharedMyGlobal;
}
- (id)init {
if (self = [super init]) {
myGreen = [[UIColor alloc] initWithRed:0.0 / 255 green:204.0 / 255 blue:51.0 / 204 alpha:1.0];
myRed = [[UIColor alloc] initWithRed:204.0 / 255 green:51.0 / 255 blue:51.0 / 204 alpha:1.0];
}
return self;
}
@end
用法:
cell.comboLabel.textColor = [[Global sharedGlobal] myGreen];
答案 0 :(得分:1)
如果您想全局使用颜色属性,那么一直调用alloc
和init
会很浪费。这是Singletons提供帮助的地方,你只需要创建它(alloc
+ init
),而不是在代码中的任何地方使用它。
在您的情况下,每次您想要阅读alloc
时都会调用myColor
,这是浪费的,考虑到您将在整个代码中使用它。
这看起来更干净:
cell.backgroundColor = [[Global sharedInstance] myColor];