gpt4 book ai didi

iphone - 类方法中的IOS内存泄漏

转载 作者:可可西里 更新时间:2023-11-01 03:57:26 24 4
gpt4 key购买 nike

在你看来,如果我有一个 NSObject 的单例子类被初始化为这样的参数:

- (MyObject *) initWithSomeParam:(NSString *)param{
self = [super init];
if (SharedInstance == nil){
SharedInstance = [super init];
SharedInstance.someProperty = param;
}
return self;
}

+ (MyObject *) objectWithSomeParam:(NSString *)param{
return [[self alloc] initWithSomeParam:param];
// Will the alloc cause a leak?
}

用户无权访问实例方法,只能访问类。谢谢。

最佳答案

这不是实现单例的正常方式,您正在打破 init 的惯例。更好的方法是创建一个 sharedInstance 类方法,并让 initWithParam 方法更常规:

static MyObject *_sharedInstance = nil;

+ (MyObject *)sharedInstance:(NSString *)param
{
if (_sharedInstance == nil)
{
_sharedInstance = [MyObject alloc] initWithParam:param];
}
return _sharedInstance;
}

// This must be called during app termination to avoid memory leak
+ (void)cleanup
{
[_sharedInstance release];
_sharedInstance = nil;
}

- (id)initWithParam:(NSString *)param
{
self = [super init];
if (self != nil)
{
self.someProperty = param;
}
return self;
}

然而,即使这样似乎也不太舒服;即,如果用户使用不同的参数调用 sharedInstance 会发生什么?也许您想保留初始化对象的 NSMutableDictionary 并根据参数创建/返回它们?

如果是这样,你会这样做:

static NSMutableDictionary _sharedInstances = [[NSMutableDictionary alloc] init];

+ (MyObject *)sharedInstance:(NSString *)param
{
MyObject *obj = [_sharedInstances objectForKey:param];
if (obj == nil)
{
obj = [[MyObject alloc] initWithParam:param];
[_sharedInstances setObject:obj forKey:param];
}
return obj;
}

// This must be called during app termination to avoid memory leak
+ (void)cleanup
{
[_sharedInstances release];
_sharedInstances = nil;
}

关于iphone - 类方法中的IOS内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10849691/

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