问题
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