Objective-C编程语言课程笔记(十一)协议(极客班)

一、协议

1、认识协议

Objective-C编程语言课程笔记(十一)协议(极客班)_第1张图片
Paste_Image.png
#import 

@protocol Drawable

@property  NSInteger x;
@property  NSInteger y;

-(void)draw;
+(void)createShape;
//-(id)init;
//-(void)dealloc;

@optional
-(void)moveToX:(NSInteger)x withY:(NSInteger)y;

@end

2、使用协议

Objective-C编程语言课程笔记(十一)协议(极客班)_第2张图片
Paste_Image.png
// -------------     定义协议    -------------
@protocol AProtocol

-(void)methodA;

@end

@protocol BProtocol 

-(void)methodB;

@end

@protocol CProtocol

-(void)methodC;

@end


// -------------     遵守协议的类    -------------

@interface ClassA : NSObject

@end

@interface ClassB : NSObject

@end

@interface ClassC : NSObject

@end

3、更多协议

Objective-C编程语言课程笔记(十一)协议(极客班)_第3张图片
Paste_Image.png
void process1(id obj)
{
    [obj draw];
    NSLog(@"[%ld,%ld]",(long)obj.x,(long)obj.y);
}

void process2(id obj){
    if ([obj conformsToProtocol:@protocol(AProtocol) ]) {
        [obj methodA];
    }
}

void process3(id obj)
{
    [obj methodA];
    [obj methodB];
}

void process4(id obj){
    
    [obj methodA];
    [obj methodC];
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        BLNPoint *point =[[BLNPoint alloc]init];
        [point draw];
        process1(point);
        [BLNPoint createShape];
        
        // ------   遵守协议  ------
        id itemA = [[ClassA alloc]init];
        process2(itemA);
        
        
        // ------   协议继承  ------
        id itemB = [[ClassB alloc]init];
        process3(itemB);
        
        // ------   协议组合  ------
        id itemC = [[ClassC alloc]init];
        process4(itemC);
        
    }
    return 0;
}

4、常用协议

Objective-C编程语言课程笔记(十一)协议(极客班)_第4张图片
Paste_Image.png

你可能感兴趣的:(Objective-C编程语言课程笔记(十一)协议(极客班))