我有一个静态类,它有两个属性,像下面…
@interface Global : NSObject
{
BarcodeScanner* scanner;
NSInteger warehouseID;
}
@property(assign) BarcodeScanner* scanner;
@property(assign) NSInteger warehouseID;
+(Global *)sharedInstance;
@end
#import "Global.h"
@implementation Global
@synthesize scanner,warehouseID;
+ (Global *)sharedInstance
{
static Global *globalInstance = nil;
if (nil == globalInstance) {
globalInstance = [[Global alloc] init];
globalInstance.scanner = [[BarcodeScanner alloc] init];
globalInstance.warehouseID = 1;
}
return globalInstance;
}
-(void) dealloc
{
[super dealloc];
}
@end
现在当我在Xcode中分析项目时,我得到了扫描仪和warehouseID属性的内存泄漏警告,当我试图在dealloc方法中释放它们时,如…
[[[Global sharedInstance] scanner]release];
i得到警告"不正确地递减对象的引用计数…"
我该如何解决这个问题?
所以谢谢你的帮助。
此警告是因为您的代码与Analyzer使用的规则不匹配。避免警告
- 使扫描仪属性保留
- 将barcodesscanner的实例化更改为自动释放
- 在dealloc中为扫描仪添加释放
示例(为了节省空间而重新格式化):
@class BarcodeScanner;
@interface Global : NSObject {
BarcodeScanner* scanner;
NSInteger warehouseID;
}
@property(retain) BarcodeScanner* scanner;
@property(assign) NSInteger warehouseID;
+(Global *)sharedInstance;
@end
@implementation Global
@synthesize scanner,warehouseID;
+ (Global *)sharedInstance {
static Global *globalInstance = nil;
if (nil == globalInstance) {
globalInstance = [[Global alloc] init];
globalInstance.scanner = [[[BarcodeScanner alloc] init] autorelease];
globalInstance.warehouseID = 1;
}
return globalInstance;
}
-(void) dealloc {
[scanner release];
[super dealloc];
}
@end
把它留给自动发布池
globalInstance。[[[BarcodeScanner alloc] init] autorelease];