gpt4 book ai didi

ios - 如何释放通过 dispatch_once 创建的实例对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:29:40 25 4
gpt4 key购买 nike

我的项目使用ARC

我有 1 个这样的类:

@implementation MyObject

+ (instancetype)shareInstance {
static id _shareInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_shareInstance = [[self alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(freeInstance)
name:kLC_Notification_FreeAllInstance object:nil];
});
return _shareInstance;
}
+ (void)freeInstance {
/*I want to release object "_shareInstance" but how??? */
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

但是我不能释放我的实例对象,所以我必须改变:

(移动代码行 static id _shareInstance = nil; +shareInstance

@implementation MyObject
static id _shareInstance = nil;
+ (instancetype)shareInstance {
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_shareInstance = [[self alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(freeInstance)
name:kLC_Notification_FreeAllInstance object:nil];
});
return _shareInstance;
}
+ (void)freeInstance {
_shareInstance = nil;
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

当我使用名称推送通知时:kLC_Notification_FreeAllInstance,所有实例对象都被释放(所有 dealloc 方法都被调用)。 没关系

但是当我再次调用它时......

所有实例都不会在下次调用时初始化。所有实例对象都将为零

我在 dispatch_once block 中设置了很多断点,但没有调用断点。


所以我的问题是:

  1. 在方法中写static id object;和在方法外写有区别吗?

  2. 我怎样才能释放所有实例对象,以便我仍然可以再次调用它们?(我想使用 ARC,我可以不用 ARC)

最佳答案

我认为你应该在释放_shareInstance时将oncePredicate设置为0

@implementation MyObject
static id _shareInstance = nil;
static dispatch_once_t oncePredicate;
+ (instancetype)shareInstance {
dispatch_once(&oncePredicate, ^{
_shareInstance = [[self alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(freeInstance)
name:kLC_Notification_FreeAllInstance object:nil];
});
return _shareInstance;
}
+ (void)freeInstance {
_shareInstance = nil;
oncePredicate = 0;
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

它对我有用!

关于ios - 如何释放通过 dispatch_once 创建的实例对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19270543/

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