Monday, December 21, 2015

Formal Protocol vs Informal Protocol

Category is an extension for class functionality - this is an implementation of some methods:
@interface NSObject (MyCategory)
  - (void)doSomething;
@end

...

@implementation NSObject (MyCategory)
  - (void)doSomething {
    // do something...
  }
@end

Formal protocol is something completely different. If you are familiar with some other object oriented language then it is like interface (in Java, C++, C# etc.).
Protocol may be attached to any class implementation like this:
@protocol MyProtocol
@required
- (void)doSomething;
@optional
- (void)doSomethingOptional;
@end

...

@interface MyClass : NSObject <MyProtocol> {
}
@end

...

@implementation MyClass
  - (void)doSomething {
    // do something...
  }
@end

According to the documentation, the informal protocols ARE categories of NSObject class (I've never used this approach):
@interface NSObject (MyInformalProtocol)
- (void)doSomething;
@end

...

@implementation NSObject (MyInformalProtocol)
  - (void)doSomething {
    // do something...
  }
@end

No comments:

Post a Comment