我正在做一个非 ARC 的项目。该项目有一个像全局函数类一样使用的单例类。
一切正常。除了以下问题:
- 添加了一个带有 ARC 的类
- 当从基于ARC的类访问单例类时,它第一次工作
- 可能它正在释放单例类,并且对单例类的进一步调用使应用程序崩溃,并显示消息“消息发送到解除分配的实例”
我可以想象启用 ARC 的类有点释放单例对象。
我该如何克服呢?
编辑:单例类初始化器 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
全局函数.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]。但是应用程序仍然崩溃并显示“发送到已释放实例”的消息