Instance variables in .h


#1

Hi, I’m just going through and enjoying the book, which really is excellent.

Why do we declare attributes in Objective C in header files, in the class interface and not in implementation? Aren’t they just internal implementation thing of the class which shouldn’t be exposed? Anyway, they are not exposed, in order to do so we need to implement accessors for them. So why are they in the interface?

Thanks,
Radek


#2

Actually, nowadays, you don’t need to declare them at all if you use properties instead. However, the compiler will synthesise them for you.
Also you can declare properties in the implementation file too; then they will be virtually private.

//  FooBarView.h

#import <UIKit/UIKit.h>

@interface FooBarView : UIView

@property (nonatomic, assign) NSInteger             barCount;
@property (nonatomic, assign) IBOutlet UITextField *barName;

@end
//  FooBarView.m

#import "FooBarView.h"

// Internal details
//
@interface FooBarView ()
@property (nonatomic, assign) NSInteger  fooCount;
@property (nonatomic, retain) NSString   *fooName;

- (void)paintFooBar;

@end

@implementation FooBarView

@synthesize barCount;
@synthesize barName;

@synthesize fooCount;
@synthesize fooName;

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)paintFooBar
{
    // ...
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end

This is worth reading: The Objective-C Programming Language in the documentation set.


#3

Ok, I didn’t know that you can declare attributes also in implementation. Then it makes sense: they are public when declared in interface and private in implementation.

(Actually I just spent some time figuring out why my code stopped working after finishing the “gold challenge” of adding a subclass and then changing the manually declared attributes into properties. I was accessing a parent’s attribute from the subclass and then it became unknown for the subclass. So thanks to my laziness - not making a copy of the project for exercises - I also learnt that the attributes generated from @property are visible only in the actual class, otherwise private :slight_smile: )

Thanks,
R.