Assume that I have this piece of code:
@interface Foo : NSObject {
Bar *bar;
}
@property (retain, nonatomic) Bar *bar;
@end
When using this field/property, is there any difference between lines:
[self.bar doStuff];
and
[bar doStuff];
?
When doing assignment, property method will perform correct retaining, but what about the read access to the property, as described above? Is there any difference?
In most cases, methods are actions and properties are qualities. Using a method causes something to happen to an object, while using a property returns information about the object or causes a quality about the object to change.
The instance method can access the both class variable and instance variables. The class method can access the class variables. The static method cannot access the class variables and static variables. Therefore, it cannot change the behavior of the class or instance state.
A property can be backed by an instance variable, but you can also define the getter/setter to do something a bit more dynamic, e.g. you might define a lowerCase property on a string which dynamically creates the result rather than returning the value of some member variable.
Objective-C properties offer a way to define the information that a class is intended to encapsulate. As you saw in Properties Control Access to an Object's Values, property declarations are included in the interface for a class, like this: @interface XYZPerson : NSObject.
There is a big difference.
[self.bar doStuff]
is equivalent to [[self bar] doStuff]
[bar doStuff]
is equivalent to [self->bar doStuff]
The former uses the accessor method, the latter just accesses the instance variable bar directly.
If you use the @synthesize
directive on your bar
property, the compiler will generate two methods for you:
- (void)setBar:(Bar*)b;
- (Bar*)bar;
Also note, that the compiler generated setter method is retaining your Bar
instance as you told it in the @property
declaration.
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