将WEAK设置为非@property变量 [英] Setting WEAK to a non @property variable

查看:167
本文介绍了将WEAK设置为非@property变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要有ARC知识的人来帮助我。



基本上,我已经在类中声明了一些变量

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

@property(nonatomic,weak)NSString * one;

正如你所看到的,我可以设置弱标识符为 NSString * one 。但是,对于 NSString * two ,我不需要getter / setter / synthesizer,因为它只是一个公共变量。如何设置 weak 标签,以便内存被释放?或者自动设置?

解决方案

您可以这样做:

  __ weak NSString * two; 

但您可能不会在这种情况下做。 / p>

声明一个实例变量 __ weak 意味着对目标对象只要一些其他对象持有一个引用。当最后一个持有强引用的对象释放该字符串时,您的变量两个将自动获得 nil 。当对象保存对彼此的引用时,例如在父子层次结构中,这是非常有用的。因为你的 NSString *两个不可能持有对你的对象的引用,使用 __ weak 引用是非常可疑的。


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?

解决方案

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.

这篇关于将WEAK设置为非@property变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆