dpbataller
dpbataller

Reputation: 1207

Declaring class attributes Objective-C

I'm starting to learn Objective-C and I have a question:

When you declare the properties of a class, what is the difference between doing this?

FIRST CASE:

@interface ViewController : UIViewController 
{
 UILabel *label;
}
@property(nonatomic,retain) UILabel *label;
@end

SECOND CASE:

@interface ViewController : UIViewController 
{

}
@property(nonatomic,retain) UILabel *label;

@end

In the first case, I'm declaring a class with one attribute (UILabel *label) and later, I'm declaring the properties for that label.

In the second case, I only declare the properties. I always thought I should declare class attributes.

Upvotes: 2

Views: 395

Answers (2)

user102008
user102008

Reputation: 31303

Another difference that has not been mentioned:

In your first case, label has protected access. Instance variables are by default @protected if not declared otherwise.

On the other hand, in the second case, label is private (at least in my compiler).

This difference matters when you have subclasses.

Upvotes: 0

JeremyP
JeremyP

Reputation: 86651

In the fist case, i'm declaring a class with one atribute (UILabel *label) and later, i'm declaring the properties for that label.

No you are not. In the first case, you are declaring an instance variable called label and a pair of accessor methoods called -setLabel: and -label (known together as a property). You have established no link between the property and the instance variable. They are at this point independent entities.

If you do this in the implementation:

@synthesize label = fooBar;

You are saying that the methods of the label property actually use a completely different instance variable to back the property.

I always thought I should declare class attributes

I used to think the same, but actually, if you are synthesizing the property, there's no point in declaring an ivar separately because the @synthesize will do it for you (and in ARC will apply the correct ownership qualifiers). I now do something like this:

 @synthesize label = label_;

so I don't use the instance variable when I mean to use the property. e.g. [label length] flags an error when I meant [[self label] length]

Also, if you change the implementation of the property to not use an instance variable, if you haven't declared the instance variable explicitly, it will go away and accidental uses of it (+ those in init and dealloc) will be flagged as errors.

Upvotes: 2

Related Questions