gpt4 book ai didi

ios - 访问实例变量导致保留周期?

转载 作者:行者123 更新时间:2023-12-01 18:13:06 27 4
gpt4 key购买 nike

如果我有:

@interface SomeClass() {
NSObject *_someObject;
}

...

- (void)someMethod {
[self doSomething:^(NSObject *someOtherObject) {
_someObject = someOtherObject;
}];
}
...

自从我们访问该块中的_someObject以来,是否会与self保持一个循环?

最佳答案

在这种情况下,self将被保留,如果您像下面这样访问类变量,它就像:

- (void)someMethod {
[self doSomething:^(NSObject *someOtherObject) {
self->_someObject = someOtherObject;
}];
}

如果创建的块在self之前被销毁,一切都会好的,但是如果block生存的时间更长,则所有其他对self的引用,self将保留在内存中,而block不会释放它。

我建议使用此代码:
@interface SomeClass()     

@property (nonatomic, strong)NSObject *someObject;

...

- (void)someMethod {
__weak SomeClass *weak_self = self;
[self doSomething:^(NSObject *someOtherObject) {
weak_self.someObject = someOtherObject;
}];
}
...

要么
@interface SomeClass() {
NSObject *_someObject;
}

...

- (void)someMethod {
__weak SomeClass *weak_self = self;
[self doSomething:^(NSObject *someOtherObject) {
__strong SomeClass *strong_self = weak_self;
strong_self->_someObject = someOtherObject;
}];
}
...

关于ios - 访问实例变量导致保留周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26618866/

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