IOS学习笔记十三(使用类别实现非正式协议)

231 阅读1分钟

1、协议

可以理解为 java 里面的接口

2、测试 Demo

NSObject+chenyu.h

#ifndef NSObject_chenyu_h
#define NSObject_chenyu_h
#import <Foundation/Foundation.h>
 
@interface NSObject(chenyu)
-(void)test;
@end
 
#endif /* NSObject_chenyu_h */

Org.h

#ifndef Org_h
 
#define Org_h
 
#import <Foundation/Foundation.h>
 
#import "NSObject+chenyu.h"
 
@interface Org : NSObject
 
@end
 
 
 
#endif /* Org_h */

Org.m

#import <Foundation/Foundation.h>
#import "Org.h"
//#import "NSObject+chenyu.h"
 
@implementation Org
//如果不实现协议中的方法会发生错误
-(void)test
{
    NSLog(@"this is org test method");
}
@end

main.m

#import "Org.h"
 
int main(int argc, char * argv[]) {
    @autoreleasepool {
        Org *org = [Org new];
        [org test];
    }
}

3、运行结果

this is org test method