This code:
__weak VeryCool *weakSelf = self;
something.changeHandler = ^(NSUInteger newIndex) {
if (newIndex == 0) {
[weakSelf.options removeObjectForKey:@"seller"];
}
};
gives me a warning that property options was not found. That's true, because options is an ivar, but not declared as property. Is it possible to somehow get options from weakSelf without declaring it as property?
For a private/protected variable, use iVar; for a public variable, use property. If you want to use the benifit of property attributes for a private variable, like retain, nonatomic etc., declare the property in the implementation file as a private property.
For an iVar, you can use @private, @protectedand @public. But these attributes only influence the access of its subclass, and has nothing to do with the access ability of its instances. Go to herefor reference. usage Directly use an iVar inside the class, for example, photographer. But use self.for a property, for example, self.photographer.
@synthesizeis only for property, not iVar. It will help the property generate an instance variable, the getter and setter accessors for the property and use the generated instance variable in the getter and setter accessors. For every property, complier will automatically synthesize it using _propertyName.
Note for property inheritance:If the super class has a property declared as public, the subclass can inherit the property. But the auto synthesize mechnism will not sythesize the property automatically, and you can only use the getter and setter accessors of the superclass by using dot operation. If you want to synthesize manually, Be Carefull!
For direct ivar access, use ->
. For example:
__weak VeryCool *weakSelf = self;
something.changeHandler = ^(NSUInteger newIndex) {
if (newIndex == 0) {
VeryCool* strongSelf = weakSelf;
if (strongSelf)
[strongSelf->options removeObjectForKey:@"seller"];
}
};
It's important to check that strongSelf
is non-nil
because direct access to an instance variable will crash for a nil
pointer (which is different from invoking methods with a nil
receiver and property access is just method invocation).
It's not possible to dereference the weak pointer directly to get the ivar; trying to do so is a compiler error due to the race condition caused by the auto-nil
behavior.
KVC will get the ivar for you, however:
[weakSelf valueForKey:@"options"]
This looks for an accessor method with the same name. If none is found, it will fall back on getting the ivar itself.
Since the reciever of the message valueForKey:
is a weak reference, it will be nil
if the object has been deallocated, making the message send a no-op. You thus avoid having to reassign self
yet again in order to manually convince the AutomaticRC to do what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With