Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between accessing property methods and class fields (Objective-C)

Tags:

objective-c

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?

like image 386
Sergey Mikhanov Avatar asked Jul 04 '09 14:07

Sergey Mikhanov


People also ask

What is the difference between a property and a method on a class?

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.

How instance methods differ from class methods in C#?

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.

What is the difference between property and instance variable?

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.

What is a property Objective C?

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.


1 Answers

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.

like image 155
nschmidt Avatar answered Oct 16 '22 16:10

nschmidt