Setting WEAK to a non @property variable

末鹿安然 提交于 2019-12-24 00:48:27

问题


Will need someone with knowledge of ARC to help me.

Basically, I have declared some variables as such in my class

@interface Class{
    NSString* one;
    NSString* two;
}

@property(nonatomic,weak) NSString* one;

As you can see, I can set the weak identifier to NSString* one. However, I do not need a getter/setter/synthesizer for NSString* two as it is just a common variable. How can I set a weak label to it so the memory is deallocated? Or is automatically set?


回答1:


You can do it like this:

__weak NSString *two;

But you probably do not want to do it in this case.

Declaring an instance variable __weak means that the reference to the target object (a string in your case) will exist only as long as some other object holds a reference. When the last object holding a strong reference releases the string, your variable two will get nil-ed out automatically. This is very useful when objects hold references to each other, such as in parent-child hierarchies. Since your NSString *two could not possibly hold a reference to your object, using the __weak reference for it is highly questionable.




回答2:


You can do this without worrying:

NSString* two = [[NSString alloc] init];

When your instance of the class Class is release for some reason, since is the only one (in theory) referencing two, it will be deallocated.




回答3:


My advice (and I think Apple's although I could be wrong) would be to get into the habit of always using properties for your iVars, then this problem goes away.



来源:https://stackoverflow.com/questions/11341818/setting-weak-to-a-non-property-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!