Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Categories vs Informal Protocols

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.

like image 429
user236739 Avatar asked Dec 06 '22 03:12

user236739


1 Answers

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
like image 156
Michael Kessler Avatar answered Dec 07 '22 15:12

Michael Kessler