1
votes

So let's say I've got a synthesized property for a UITextField which I have named field1. From my understanding is that you should use self.field1 = newValue to change the field1 value. By using the dot notation you automatically use the created setter by the compiler. (Or use it without dot notation [self setField1:newValue])

But I've seen examples where they use this same dot notation method on setting the field1's ivars like:

field1.text = @"Text";

Does this mean that when declaring a property you can automatically use dot notation on all that property's ivars? Or is this possible only because in that UITextField class the ivar "text" is declared as a property? Say if text wasn't declared as a property would the correct way to set the text ivar be:

[field1 setText:@"Text"]
5

5 Answers

20
votes

Given:

@interface Foo:NSObject
{
   int bar;
}

@property int age;

- (int)bar;
- (void)setBar:(int)anInt;
@end

@implementation Foo
@synthesize age;

- (int)bar { return bar; }
- (void)setBar:(int)anInt { bar = anInt; }
@end

You can:

- (void)makeMyFunkThePFunk
{
   Foo *foo = [Foo new];
   foo.bar = 5;
   [foo setBar: 42];

   [foo setAge: 29];
   foo.age = 42;

   [foo setAge: foo.bar];
   [foo setBar: foo.age];
}

@property is nothing more than a bit of syntax for declaring setter/getter methods more easily, including the automatic synthesis of both the instance variables and the implementation methods, if desired.

The dot syntax is shorthand for a method call. Any "dot" expression can be turned into an equivalent method call and using the dot syntax does not require an @property declaration.

2
votes

Or is this possible only because in that UITextField class the ivar "text" is declared as a property?

This is correct. You can use the dot notation on anything that's declared as a property.

2
votes
field1.text = @"Text";

and

[field1 setText:@"Text"]

are equivalent, and you would expect them to be, but field1.text could call almost any method if the property was defined differently: @property(getter=someOtherMethod)NSString * text;

1
votes

Property declarations do not apply automatically to ivars' components.

In your example,

field1.text = @"Text";

text is also declared as a property in UITextField. This is why you can use it like that.

0
votes

You can access the property of properties with dot notation.

self.field1.text = @"test";

There's nothing special going on. self.field1 returns a UITextField. text is the name of a property of that text field.


In response to your comment, self.field1 accesses the property, field1 is the ivar. My example given above is exactly equivalent to:

[[self field1] setText:@"test"];

Either one will work, but you generally want to use the property accessors like: self.field1.text