認識協議
//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