[英]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.