目标 C 中 self.variable 和变量赋值的区别 [英] Objective C difference between self.variable and variable assignments
问题描述
我怕我很笨.
我花了大约三个小时来追踪破坏我理智的内存泄漏,在注释掉我的一半应用后,我得出了以下结论.
I've spent about three hours tracking down a memory leak that's been destroying my sanity and after commenting out half my app I have come to the following conclusion.
在正确的位置给出以下内容.
Given the following in the right places.
NSString *blah;
@property (nonatomic, retain) NSString *blah;
@synthesize blah;
-(id)initWithBlah:(NSString*)b {
self.blah = b; //this leaks
blah = b; //this does not
}
我对objectice c 不是特别有经验,我知道如果我在课堂之外调用object.blah = b;我会透明地调用一个 setter 函数,该函数将保留 b.在我通过设置 self.blah = b 假设的函数内部,我出于某种原因双重保留?
I am not particularly experienced with objectice c, I understand that outside of the class if I were calling object.blah = b; I would be transparently calling a setter function which would retain the b. Inside the function I'm presuming by setting it with self.blah = b I'm double retaining for some reason?
有人可以向我解释为什么会这样,或者如果不是的话,我可能做错了什么?
Could someone explain to me why that's the case or if not what I might be doing wrong?
干杯
推荐答案
你错了.blah = b;
赋值意义不大,因为在您的代码从 initWithBlah:
返回后,您不能再依赖周围的字符串.每当您下次访问它时,它很可能已经被释放.
You are mistaken. The blah = b;
assignment makes little sense because after your code returns from initWithBlah:
you can no longer rely on the string being around. Whenever you access it next, it has very probably already been deallocated.
self.blah = b;
赋值是正确的,因为它调用了 setter,因此你获得了字符串的所有权.当然,您也必须在 -dealloc
中释放 blah
以防止内存泄漏.
The self.blah = b;
assignment is correct because it calls the setter and thereby you take ownership of the string. Of course, you have to release blah
in your -dealloc
, too, to prevent memory leaks.
这篇关于目标 C 中 self.variable 和变量赋值的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!