我正在开发一个非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
编辑:
尝试使用[[GlobalFunctions alloc] init]作为Anshu建议的。但仍然是应用程序崩溃,并显示消息“已发送到已取消分配的实例”
答案 0 :(得分:4)
首先,删除copyWithZone:
,retain
和retainCount
方法;他们在单身人士中毫无用处。
其次,dealloc
方法错了; [super dealloc]
必须始终是最后一个语句。
问题在于你的单身人士;您覆盖retain
不执行任何操作,但不要覆盖release
。 ARC'd课程可能会在范围的开头调用retain
,最后调用release
。由于单例的release
实际上仍然减少了保留计数,因此单例被解除分配。
删除上面提到的各种方法,它应该可以正常工作。
请注意,您的GlobalFunctions
类不应声明为实现<UIApplicationDelegate>
,因为它不是应用程序的委托。此外,有两种方法来获取相同的托管对象上下文是奇怪的(但不是致命的)。