我不得不開發一個兼容OSX 10.6到最新版本的應用程序,這需要手動管理內存。在這個應用程序中,我想將所有的顏色都放在一個地方,並通過appDelegate的屬性訪問它。使用NSColor和CGColor管理內存的最佳方法
我的第一個方法是使用NSColor對象:
@property (strong, nonatomic) NSColor *myBlue;
@synthesize myBlue = _myBlue;
_myBlue = [[NSColor colorWithCalibratedRed:20.0/255.0 green:20.0/255.0 blue:0.0/255.0 alpha:1.0/1.0] retain];
而且我釋放它的appDelegate的dealloc方法:
[_myBlue release];
當我需要一個NSColor另一個類,我訪問做:
appDelegate.myBlue
如果我需要一個CGColor,我用這個功能:
- (CGColorRef)NSColorToCGColor:(NSColor *)color
{
NSInteger numberOfComponents = [color numberOfComponents];
CGFloat components[numberOfComponents];
CGColorSpaceRef colorSpace = [[color colorSpace] CGColorSpace];
[color getComponents:(CGFloat *)&components];
CGColorRef cgColor = CGColorCreate(colorSpace, components);
return cgColor;
}
view.layer.backgroundColor = [[GlobalFunctions sharedGlobalFunctions] NSColorToCGColor:appDelegate.myBlue]];
但是這個函數已知會導致內存泄漏,因爲對象cgColor從不釋放。注意:我需要使用此功能,因爲使用OSX 10.6 SDK時,我無法使用myBlue.CGColor從NSColor生成CGColor。
我的第二個方法是使用CGColor這樣的:
@property (nonatomic) struct CGColor *myRed;
@synthesize myRed = _myRed;
_myRed = CGColorCreateGenericRGB(20.0/255.0, 20.0/255.0, 255.0/255.0, 1.0/1.0);
而且我釋放它的appDelegate的dealloc方法:
CGColorRelease(_myRed);
當我在另一個類需要一個CGColor,我訪問它在做:
appDelegate.myRed
如果我需要一個NSColor,我使用這個函數:
textView.textColor = [NSColor colorWithCIColor: [CIColor colorWithCGColor: appDelegate.myRed]];
最後,問題是:什麼是管理NSColor和CGColor的最佳實踐,以避免內存泄漏並優雅地執行它?