Sian 发表于 2014-1-20 21:40:40

第二十一讲:Objective-C基本数据结构之协议

本帖最后由 Sian 于 2014-1-20 22:11 编辑

1、什么是协议
2、如何定义协议
3、如何实现协议
MyProtocol.h
//
//MyProtocol.h
//Protocol
//
//Created by yusian on 14-1-20.
//Copyright (c) 2014年 yusian. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol MyProtocol <NSObject>

@required
- (int)printValue:(int)value1 andValue:(int)value2;

@optional
- (void)print:(int)value;

@end


MyTest.h
//
//MyTest.h
//Protocol
//
//Created by yusian on 14-1-20.
//Copyright (c) 2014年 yusian. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "MyProtocol.h"

@interface MyTest : NSObject <MyProtocol>

- (void)showInfo;

@end
MyTest.m
//
//MyTest.m
//Protocol
//
//Created by yusian on 14-1-20.
//Copyright (c) 2014年 yusian. All rights reserved.
//

#import "MyTest.h"

@implementation MyTest

- (void)showInfo
{
    NSLog(@"showInfo is calling");
}

- (int)printValue:(int)value1 andValue:(int)value2
{
    NSLog(@"printValue is %d, printValue is %d",value1,value2);
    return 0;
}

- (void)print:(int)value
{
    NSLog(@"print is %d",value);
}

@end
main.m
//
//main.m
//Protocol
//
//Created by yusian on 14-1-20.
//Copyright (c) 2014年 yusian. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "MyTest.h"
#import "MyProtocol.h"
int main(int argc, const char * argv[])
{

    @autoreleasepool {
      
      MyTest * myTest = [ init];
      
      ;
      
//**************************************************
//实现方法一:
      NSLog(@"实现方法一:");
      ;
      
      SEL sel = @selector(print:);
      if () {
            ;
      }
      
      ;

//**************************************************
//实现方法二:
      NSLog(@"实现方法二:");
      id <MyProtocol> myTest_Protocol = [ init];
      
      ;
      
      if () {
            ;
      }
      ;
//**************************************************
      
    }
    return 0;
}
输出结果:
2014-01-20 21:38:06.164 Protocol showInfo is calling
2014-01-20 21:38:06.165 Protocol 实现方法一:
2014-01-20 21:38:06.166 Protocol printValue is 10, printValue is 20
2014-01-20 21:38:06.166 Protocol print is 100
2014-01-20 21:38:06.166 Protocol 实现方法二:
2014-01-20 21:38:06.167 Protocol printValue is 100, printValue is 200
2014-01-20 21:38:06.167 Protocol print is 1000
Program ended with exit code: 0

页: [1]
查看完整版本: 第二十一讲:Objective-C基本数据结构之协议