Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for'@interface ViewController' in both the implementation and header file for a viewcontroller

Why do we have the '@interface ViewController' line in both the implementation and header file for a viewcontroller in xcode?

like image 667
Jay Jay Jay Avatar asked Apr 07 '13 02:04

Jay Jay Jay


1 Answers

It's to do with the visibility of the contents of the @interface. When it's contained within the header file, it's available for other classes to see when they import the header file. When it's contained within the implementation file, the contents are only available to that implementation file alone. Typically when it's declared within the implementation file, it is done via a class extension (i.e. @interface ClassName (), the () denotes a class extension/anonymous category), although a named category can be used if so desired.

There are a few reasons why this is done. The main one is to define private instance variables or properties. You don't want these to be exposed to everyone who imports the header file, but you need a place to store internal information. For example, this will allow m_isActive to be used within the implementation only:

@interface Class () {
    BOOL m_isActive;
}

You can also override readonly properties declared in the header file, so that the implementation file has readwrite access to it when using dot notation. For example:

Header:

@interface Class
@property (nonatomic, readonly) NSString* name;
@end

Implementation:

@interface Class ()
@property (nonatomic) NSString* name;
@end

@implementation Class
...
    self.name = @"WDUK"; // This is allowed, as the class extension has overridden the readonly attribute via a redeclaration of the property
...
@end

Another popular use is to privately declare that you conform to particular protocols, which is an implementation detail and does not need to be exposed within the public header file. For example, when the implementation uses an object that requires it to be a delegate, and you don't want to pollute the header file with a protocol that isn't used outside the class.

Other uses (which have been left in the dark with recent LLVM/Clang improvements) were to define private methods. This is no longer required, as the compiler will look for methods not declared within the respective header file, and assume they are private to the class and declare them itself.

The key part to take from all this, is that anything within @interface within the header file (Except instance variables defined there via @private or @protected) are public, and anything within the implementation file is inherently private.

like image 109
WDUK Avatar answered Nov 15 '22 07:11

WDUK