Objective-C Protocol and Catalog

Protocol

Objective-C protocol is similar to interface in Java

Define a protocol in a header file

@protocol StringUtils

-(void) outputString;

@optional
-(void) outputOptionalString;

@required
-(void) outputString2;

@end
  • @optional declares any optional methods
  • @required declares all required methods (default)

Extending a protocol

@protocol TextUtils < StringUtils, CharUtils >

Define an interface supporting a protocol (Adopting a protocol)

#import "StringUtils.h"

@interface MyString: NSObject <StringUtils, SomeOtherProtocol> {
   ...
}

...
@end

Implementation Code

#import "MyString.h"

@implementation MyString
...

-(void) outputString {
...
}

-(void) outputString2 {
...
}

...
@end

To confirm an object confirm to (support) a protocol

[obj1 conformsToProtocol:@protocol(StringUtils)]

Declare an object confirm to a protocol

MyString <StringUtils> *obj1;
id <StringUtils> *obj2;

Category

Objective-C category add methods to an existing class without extending the class. This allows adding new methods to an existing class

For example, adding a new validation method to the build-in NSString class

#import <Cocoa/Cocoa.h>
            
@interface NSString (Validation)
- (BOOL) isPhoneNumber;
@end
#import "NSString-Validation.h"
            
@implementation NSString (Validation)

- (BOOL) isPhoneNumber
{
  ...
}
@end
  • Category cannot add new instance variable
  • Category can override existing method