认识协议
//Drawable.h 文件
#import <Foundation/Foundation.h>
@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
使用协议
只出现警告信息而不是错误,是因为有运行时添加方法的机制。所以编译器会认为这样也未必就是错误。
#import <Foundation/Foundation.h>
#import "Drawable.h"
@interface BLNPoint : NSObject<Drawable> // 用<>准守协议
@property NSInteger x;
@property NSInteger y;
// 协议的属性也可以不在头文件声明,直接自己创建实例变量和getter/setter方法。但是很少如此使用。
@end
// 作为类型约束使用
void process1(id<Drawable> 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<BProtocol> obj)
{
[obj methodA];
[obj methodB];
}
// - (BOOL)conformsToProtocol:(Protocol *)aProtocol;
if ([obj conformsToProtocol:@protocol(AProtocol) ]) {
[obj methodA];
}
更多协议模式
// ------------- 定义协议 -------------
@protocol AProtocol
-(void)methodA;
@end
@protocol BProtocol <AProtocol>
-(void)methodB;
@end
@protocol CProtocol
-(void)methodC;
@end
@protocol Protocol
// 默认会有一个@require。加了@optional之后,在再次遇到@require之前都会是可选性的。
@require
-(void)methodD;
@optional
-(void)moveToX:(NSInteger)x withY:(NSInteger)y;
@end
// ------------- 遵守协议的类 -------------
@interface ClassA : NSObject<AProtocol>
@end
@interface ClassB : NSObject<BProtocol>
@end
@interface ClassC : NSObject<AProtocol,CProtocol>
@end
常用协议
@protocol NSObject
- (BOOL)isEqual:(id)object;
@property (readonly) NSUInteger hash;
@property (readonly) Class superclass;
- (Class)class OBJC_SWIFT_UNAVAILABLE("use 'anObject.dynamicType' instead");
- (instancetype)self;
- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)object;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
- (BOOL)isProxy;
- (BOOL)isKindOfClass:(Class)aClass;
- (BOOL)isMemberOfClass:(Class)aClass;
- (BOOL)conformsToProtocol:(Protocol *)aProtocol;
- (BOOL)respondsToSelector:(SEL)aSelector;
- (instancetype)retain OBJC_ARC_UNAVAILABLE;
- (oneway void)release OBJC_ARC_UNAVAILABLE;
- (instancetype)autorelease OBJC_ARC_UNAVAILABLE;
- (NSUInteger)retainCount OBJC_ARC_UNAVAILABLE;
- (struct _NSZone *)zone OBJC_ARC_UNAVAILABLE;
@property (readonly, copy) NSString *description;
@optional
@property (readonly, copy) NSString *debugDescription;
@end
@protocol NSCopying
- (id)copyWithZone:(nullable NSZone *)zone;
@end
@protocol NSMutableCopying
- (id)mutableCopyWithZone:(nullable NSZone *)zone;
@end
@protocol NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder; // NS_DESIGNATED_INITIALIZER
@end
@protocol NSFastEnumeration
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])buffer count:(NSUInteger)len;
@end