#import <Foundation/Foundation.h> @protocol Add <NSObject> - (int)addA:(int)a b:(int)b; @end #import <Foundation/Foundation.h> @protocol Sub <NSObject> - (int)subA:(int)a b:(int)b; @end #import <Foundation/Foundation.h> @protocol Mul <NSObject> - (int)mulA:(int)a b:(int)b; @end ==================================================以上是三個協議 下面是新建一個繼承與NSObject的計算類Calculator #import <Foundation/Foundation.h> #import "Add.h" #import "Sub.h" #import "Mul.h" //遵照多個協議 //相似於c++的多繼承 @interface Calculator : NSObject <Add,Sub,Mul> @end #import "Calculator.h" @implementation Calculator - (int)addA:(int)a b:(int)b { return a+b; } - (int)subA:(int)a b:(int)b { return a-b; } - (int)mulA:(int)a b:(int)b { return a*b; } @end ========================================== #import <Foundation/Foundation.h> #import "Calculator.h" /* 如今有多個類,一個是加法器類(會算加法) 第二個類是減法器類(減法功能)第三個乘法器類(乘法) 實現一個類分別能夠進行+- c++能夠用多繼承實現 可是OC沒有多繼承 可是OC能夠經過協議來實現 */ int main(int argc, const char * argv[]) { @autoreleasepool { Calculator *calc = [[Calculator alloc] init]; NSLog(@"%d",[calc addA:1 b:1]);//2 NSLog(@"%d",[calc subA:1 b:1]);//0 NSLog(@"%d",[calc mulA:1 b:1]);//1 } return 0; }