gpt4 book ai didi

ios - 如何解决单例类泄漏问题?

转载 作者:行者123 更新时间:2023-11-28 19:02:05 26 4
gpt4 key购买 nike

我在 Singleton_Newmark.h 文件中使用了以下代码

#import <Foundation/Foundation.h>

@interface Singleton_Newmark : NSObject
{

NSString *strxpos;
NSString *strypos;
NSString *strindex;
NSString *strtag;



}
@property (nonatomic) NSString *strxpos;
@property (nonatomic) NSString *strypos;
@property (nonatomic) NSString *strindex;
@property (nonatomic) NSString *strtag;


+(Singleton_Newmark *)sharedInstance;
@end



Following code used Singleton_Newmark.m file

#import "Singleton_Newmark.h"

@implementation Singleton_Newmark
@synthesize strxpos,strypos,strindex,strtag;
+(Singleton_Newmark *)sharedInstance
{
static Singleton_Newmark *sharedInstance = nil;
if (!sharedInstance) {
sharedInstance=[[Singleton_Newmark alloc]init];
}
return sharedInstance;
}

-(void)dealloc
{
strxpos=nil;
strypos=nil;
strindex=nil;
strtag=nil;
}
@end

我在单例类对象中插入值。

Singleton_Newmark *obj=[[Singleton_Newmark alloc]init];
obj.strxpos=@"Some string";
obj.strypos=@"Some string";
obj.strindex=@"Some string";
obj.strtag=@"Some string";

再次从单例类对象中读取

Singleton_Newmark *obj=[Singleton_Newmark sharedInstance];
obj=[Dict objectForKey:@"forkey"];

我在这里收到来自分析的泄漏消息:

 Value stored to 'obj' during its initialization is never read

但是我在最后一行收到了分析泄漏错误(再次阅读...)。如何解决这个问题?

最佳答案

单例模式的正确实现方式是隐藏init方法。您可以通过以下方式实现:

- (id)init __attribute__((unavailable("cannot use init for this class, use +(Singleton_Newmark*)sharedInstance instead")));

这将阻止用户使用init 方法。所以他们将被迫只使用 sharedInstance 方法。这将为您提供干净的代码表示,即使您将其发布为库也是如此。

这是您将在方法中编写的内容:

+ (Singleton_Newmark *)sharedInstance {
static Singleton_Newmark *sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [self new];
});
return sharedInstance;
}

关于ios - 如何解决单例类泄漏问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23927515/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com