I think I understood the difference between (formal) Protocols and Categories. Now, if I got it right, informal protocols should be categories (usually defined on NSObject) which are used for certain purposes (maybe to give the chance to implement only a part of the methods listed in it, unlike formal protocols). I need to be sure about it: could anyone confirm that an Informal Protocol just IS a Category (or explain the differences)? Thank you.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With