首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Objective-C 協議 完整指南:定義、可選方法與代理模式實戰

     編輯:關於C語言

什麼是協議

協議 定義了一組方法簽名,聲明了實現者需提供的行為。類似 C++ 純虛類或 Java 接口,實現了「接口與實現分離」。

  • 多對象間通信契約
  • 提供方法列表供實現者遵循
  • 支持 @required (默認) 與 @optional 方法
  • 可繼承自 NSObject 協議,支持多協議繼承

協議定義語法

@protocol MyProtocol <NSObject>

@optional
- (void)init;

@required
- (int)update:(int)time;

@end

類遵循協議

在介面聲明中尖括號內列出協議名:

@interface TestProtocol : NSObject <MyProtocol>
{
}
- (void)testValue:(int)value;
@end

方法實現

@implementation TestProtocol
- (void)testValue:(int)value {
    NSLog(@"testValue: %d", value);
}
- (int)update:(int)time {
    NSLog(@"update: %d", time);
    return 0;
}
- (void)printValue:(int)value {
    NSLog(@"printValue: %d", value);
}
@end

運行時檢查方法是否實現

利用 respondsToSelector: 動態判斷:

SEL sel = @selector(printValue:);
if ([testPtcl respondsToSelector:sel]) {
    [testPtcl printValue:20];
}

協議類型變量 (id<Protocol>)

可聲明協議類型變量,實現面向接口編程:

id <MyProtocol> myProtocol = [[TestProtocol alloc] init];
[myProtocol printValue:103]; // 僅可調用協議中聲明的方法
[myProtocol release];

完整 Demo 程序結構

// MyProtocol.h
@protocol MyProtocol <NSObject>
@optional - (void)printValue:(int)value;
@required - (int)printValue:(int)v1 andValue:(int)v2;
@end

// TestProtocol.h
#import "MyProtocol.h"
@interface TestProtocol : NSObject <MyProtocol>
- (void)testValue:(int)value;
@end

// TestProtocol.m 實現所有方法...

// main.m
#import "TestProtocol.h"
int main() {
    @autoreleasepool {
        TestProtocol *obj = [[TestProtocol alloc] init];
        [obj testValue:2];
        [obj printValue:30 andValue:40];
        if ([obj respondsToSelector:@selector(printValue:)]) {
            [obj printValue:20];
        }
        id<MyProtocol> proto = [[TestProtocol alloc] init];
        [proto printValue:103];
        [obj release]; [proto release];
    }
    return 0;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved