开始四处寻找全局静态,在一个地方设置颜色,以在整个应用程序中使用。我无法理解关于 SO 上单例的一些非常好的答案(较旧的),所以我创建了一个类来非常简单地处理这个问题。基于一些(其他线程),我决定避免应用程序委托(delegate)。
似乎有几种方法可以处理这个问题。作为一个低经验的 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];
最佳答案
好吧,如果您想在全局范围内使用您的颜色属性,那么一直调用 alloc
和 init
是一种浪费。这是单例来帮忙的地方,因为你只创建一次(alloc
+ init
),而不是在代码中的任何地方使用它。
在您的情况下,每次您想阅读 myColor
时都会调用 alloc
,考虑到您将在整个代码中使用它,这是一种浪费。
这看起来干净多了:
cell.backgroundColor = [[Global sharedInstance] myColor];
关于ios - 单例或独立类(class) - 优点和缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10195475/