我使用以下代码创建了sharedInstance
:
+ (MyClass *)sharedStore
{
@synchronized(self)
{
if (sharedInstance == nil)
sharedInstance = [[self alloc] init];
}
return sharedInstance;
}
我在MyClass
- (MyClass *)initService:(int)serviceType areaSelected :(int)areaID target:(id)delegate
{
self = [super init];
// again init function is called after having a shared instance which is resulting in memory leak.
if(self)
{
jsonParserObject = [[MyClassInfoParser alloc]init];
if(jsonParserObject != nil)
{
serviceTypeRequested = serviceType;
selectedAreaId = areaID;
NSString *url = [self createUrlandBodyForService];
NSLog(@"URL : %@",url);
if ([Reachability connected])
{
if(url.length)
{
BOOL status = [self initRequest:url withDelegate:delegate];
if(status)
NSLog(@"Request for fields successfully");
else
NSLog(@"Failed to send request for fields");
}
else
{
[super responseFailedNotification:nil];
}
}
else
{
[super networkError:delegate];
}
}
}
return self;
}
要调用上面的函数,我使用代码
- (void)startServiceForInformation
{
serviceObj = [[MyClass sharedStore]initService:2 areaSelected:self.areaId target:self];
[serviceObj start];
}
这导致内存泄漏导致崩溃。任何人都可以帮我解决这个内存泄漏问题吗?
答案 0 :(得分:1)
那么,为什么在使用singleton类时还有另一个init方法?对于第二个init方法,不需要使得该方法只需用你的单例实例调用它
试试这个
- (void)startService:(int)serviceType areaSelected :(int)areaID target:(id)delegate
{
jsonParserObject = [[MyClassInfoParser alloc]init];
if(jsonParserObject != nil)
{
serviceTypeRequested = serviceType;
selectedAreaId = areaID;
NSString *url = [self createUrlandBodyForService];
NSLog(@"URL : %@",url);
if ([Reachability connected])
{
if(url.length)
{
BOOL status = [self initRequest:url withDelegate:delegate];
if(status)
NSLog(@"Request for fields successfully");
else
NSLog(@"Failed to send request for fields");
}
else
{
[super responseFailedNotification:nil];
}
}
else
{
[super networkError:delegate];
}
}
}
并致电
- (void)startServiceForInformation
{
serviceObj = [[MyClass sharedStore]startService:2 areaSelected:self.areaId target:self];
[serviceObj start];
}
答案 1 :(得分:1)
没有必要在第二个函数中调用[super init],假设它们都在同一个类中,我推断是由于你的评论。
由于这是一个实例函数而不是像你的第一个静态函数,所以你在一个对象上调用它。在覆盖NSObject init
的大多数情况下,您有一个由类alloc
选择器创建的可靠的裸对象。
在这种情况下,您只是配置已创建的对象。你确定需要单一界面吗?