这是代码
+ (SalesCollection*)sharedCollection {
@synchronized(self) {
if (sharedInstance == nil) {
[[self alloc] init]; // assignment not done here
}
}
return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [super allocWithZone:zone];
return sharedInstance; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release {
/* Problem in Here */
[myDict release];
sharedInstance = nil;
[sharedInstance release];
}
- (id)autorelease {
return self;
}
// setup the data collection
- init {
if (self = [super init]) {
[self setupData];
}
return self;
}
这里是我的.h文件
@interface MyCollection : NSObject {
NSMutableDictionary *myDict;
}
@property (nonatomic,retain) NSMutableDictionary * myDict;
+ (MyCollection*)sharedInstance ;
- (void)setupData;
我有一个 NSMutableDictionary(myDict),其中包含对象数组。 现在我的问题是我想在按钮点击时刷新这些数据。所以我在 - (void)release 方法中发布了这个实例,然后再次尝试初始化,但这会产生大量泄漏,因为它可能不会从 myDict 中释放对象数组 所以如何实现这一目标。我按照苹果的相同例子“TheElement”创建单身。
由于
答案 0 :(得分:1)
你应该想出一些其他方法来刷新对象,而不是释放它。单身人士的全部意义在于,只能有一个,而且不会创造更多。目前还不清楚myDict是什么,但如果它是一个实例变量,也许你可以添加一个这样的方法:
- (void) refresh {
[myDict release];
myDict = nil;
[self setupData];
}
答案 1 :(得分:1)
如果您想摆脱代码分析器警告,请执行以下操作:
static SalesCollection gSharedSalesCollection = NULL;
+ (id) sharedCollection {
@synchronized(self) {
if (gSharedSalesCollection == nil) {
gSharedSalesCollection = [[self alloc] init];
}
}
return gSharedSalesCollection;
}
并使用常规的init和dealloc方法。这样,您可以将该类用作单例(通过使用sharedCollection访问它),或者将其用作非单例,例如使用常规alloc / init / release样式的单元测试。
答案 2 :(得分:0)
我找到了一种方法......这就是我在做的事情
[self performSelectorInBackground:@selector(refreshData:) withObject:overlayView];
然后我在autoreleasepool中包装了refreshData,就像这个
一样NSAutoreleasePool *arPool = [[NSAutoreleasePool alloc] init];
[[MyCollection sharedCollection] refresh];
[arPool release];
突然间所有泄漏都会......就像魅力.....(:)))))