[英]Singleton functions in a project with ARC and non-ARC?
我正在從事非ARC項目。 該項目有一個單例類,其用法類似於全局函數類。
一切正常。 除了以下問題:
我可以想象啟用了ARC的類可以釋放單例對象。
我該如何克服呢?
編輯:Singleton類初始化程序GlobalFunctions.m
#import "GlobalFunctions.h"
#import <CoreData/CoreData.h>
#import "UIImage+Tint.h"
#import "Reachability.h"
#if !TARGET_IPHONE_SIMULATOR
#define Type @"Device"
#else
#define Type @"Simulator"
#endif
@implementation GlobalFunctions
#pragma mark {Synthesize}
@synthesize firstLaunch=_firstLaunch;
@synthesize context = _context;
#pragma mark {Initializer}
static GlobalFunctions *sharedGlobalFunctions=nil;
- (UIColor *)UIColorFromRGB:(NSInteger)red:(NSInteger)green:(NSInteger) blue {
CGFloat nRed=red/255.0;
CGFloat nBlue=green/255.0;
CGFloat nGreen=blue/255.0;
return [[[UIColor alloc]initWithRed:nRed green:nBlue blue:nGreen alpha:1] autorelease];
}
#pragma mark {Class Intialization}
+(GlobalFunctions *)sharedGlobalFunctions{
if(sharedGlobalFunctions==nil){
// sharedGlobalFunctions=[[super allocWithZone:NULL] init];
sharedGlobalFunctions=[[GlobalFunctions alloc] init]; //Stack Overflow recommendation, does'nt work
// Custom initialization
/*
Variable Initialization and checks
*/
sharedGlobalFunctions.firstLaunch=@"YES";
id appDelegate=(id)[[UIApplication sharedApplication] delegate];
sharedGlobalFunctions.context=[appDelegate managedObjectContext];
}
return sharedGlobalFunctions;
}
-(id)copyWithZone:(NSZone *)zone{
return self;
}
-(id)retain{
return self;
}
-(NSUInteger) retainCount{
return NSUIntegerMax;
}
-(void) dealloc{
[super dealloc];
[_context release];
}
@end
GlobalFunctions.h
#import <Foundation/Foundation.h>
@interface GlobalFunctions : NSObject<UIApplicationDelegate>{
NSString *firstLaunch;
}
+(GlobalFunctions *)sharedGlobalFunctions; //Shared Object
#pragma mark {Function Declarations}
-(UIColor *)UIColorFromRGB:(NSInteger)red:(NSInteger)green:(NSInteger) blue; // Convert color to RGB
#pragma mark {Database Objects}
@property (nonatomic,retain) NSManagedObjectContext *context;
@end
編輯:
如Anshu建議使用[[GlobalFunctions alloc] init]進行了嘗試。 但是應用仍然崩潰,並顯示消息“已發送到已釋放實例”
首先,刪除copyWithZone:
retain
和retainCount
方法; 他們在單例中毫無用處。
其次,那個dealloc
方法是錯誤的。 [super dealloc]
必須始終是最后一個語句 。
問題出在你的單身漢身上。 您覆蓋了retain
不執行任何操作,但不覆蓋了release
。 ARC的類很可能在作用域的開頭調用“ retain
,在結尾處調用“ release
”。 由於單例的release
實際上仍會減少保留計數,因此將單例釋放。
刪除上面提到的各種方法,它應該可以正常工作。
請注意,不應將您的GlobalFunctions
類聲明為實現<UIApplicationDelegate>
因為它不是應用程序的委托。 同樣,用兩種方法來獲取相同的管理對象上下文是奇怪的(但不是致命的)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.