id type
This type defines a variable whose type is defined at runtime.
Category
Categories is used to add methods to an existing class without inheriting from it. For example, to add method <function name> to class <class to add methods>, we need to declare:
#import <Foundatiion/....h> // class we want to add methods to
@interface <class to add methods> (<name of category>)
- (<return type>) <function name>;
@end
and implement in another file:
#import <....h> // header file with declaration
@implementation <class to add methods> (<name of category>)
- (<return type>) <function name> {
// insert code for implementation
}
@end
Portocol
This is the same as interface in other programming languages. To declare:
@protocol <name of interface>
- (<return type>) <required function name>;
- (<return type>) <required function name>;
@optional
// everything after the above directive is not required, otherwise
// the class supporting the interface must implement the first 2 methods
- (<return type>) <optional function name>;
@required
// everything after the above directive is required.
- (<return type>) <required function name>;
@end
To adopt to an interface (must implement required methods from interface1
, interface2
, etc.):
@interface name : parent <interface1, interface2...>
You can check at runtime if object conforms to an interface by sending a conformsToProtocol
message:
if ([<object> conformsToProtocol:@protocol(<interface>)]) {
// do something
}
When declaring a method, it is possible to require interface
to be supported by parameters:
- (<return type>) <function name>: (id <interface>) param0;
Here param0
can be any type (due to id
), as long as the type implements interface
.