iOS协议

作者: qui丶MyLove | 来源:发表于2021-07-20 22:55 被阅读0次

协议是什么?
协议是指定了一个行为规范,遵守协议的类需要实现必要的行为。通俗说就是协议指定了一些函数声明,遵守协议的类需要实现必要的函数和选择性实现非必要的函数。

ios中的正式协议和非正式协议

非正式协议就是类别(category)
正式协议 protocol

protocol

协议声明的方法有两种,一种是必须实现的函数用@required修饰,一种是非必须实现的函数用@optional修饰,系统默认是@required。

@protocol protocolTesting <NSObject>
@required //必须实现方法
-(void)test1;
+(void)test2;
@optional//选择实现方法
-(void)test3;
@end

注释:协议是可以声明属性的,使用方法如下:

@interface ProtocolOBJ(){
    NSString *_str;
}
@end
- (void)setStr:(NSString *)str{
    _str = str;
}

- (NSString *)str{
    return _str;
}

重写get set 方法 指定成员。或者通过关键字@synthesize 告诉编译器自动生成set get 成员。

@synthesize str;
协议的继承机制

就像其它Objective-C类可以继承一样,协议也有类似的机制,我们可以使得一个协议遵循另一个协议。
在协议的写法中就可以看出我们通常制定的协议都是遵守了NSObject协议。

@protocol protocolTesting <NSObject>

一个协议遵守了另一个协议那么这个协议就获得了遵守的协议的所有方法声明不需要再去声明,同时遵守了这个协议的类就需要实现两个协议的方法。

@protocol protocolTesting <NSObject>

@required //必须实现方法
-(void)test1;
+(void)test2;

@optional//选择实现方法
-(void)test3;
@property(nonatomic) NSString *str;

@end

@protocol protocolTesting1 <protocolTesting>
-(void)test4;
@end

@interface ProtocolOBJ : NSObject<protocolTesting1>
-(void)test;
@end

@interface ProtocolOBJ(){
    NSString *_str;
}
@end
@implementation ProtocolOBJ

@synthesize str;// = _str;

- (void)test1 {
    NSLog(@"test1");
}

+ (void)test2 { 
    NSLog(@"test2");
}

- (void)setStr:(NSString *)str{
    _str = str;
}

- (NSString *)str{
    return _str;
}
- (void)test {
    self.str = @"d";
    NSLog(@"%@",self.str);
}
- (void)test4 {
    ///
}

@end

协议使用
  • 协议一般配合代理模式,协议代理模式。在ios中常见如UITableview的使用。
  • 实现类似多继承:子类遵守多个协议实现协议方法,可以通过控制遵协议位置控制方法的公开和私有。
@protocol protocolTesting1 <protocolTesting>
-(void)test4;
@end

@protocol protocolTesting2 <NSObject>
-(void)test6;
@end

@protocol protocolTesting3 <NSObject>
-(void)test6;
@end


@interface ProtocolOBJ : NSObject<protocolTesting1,protocolTesting2,protocolTesting3>

- (void)test4 {
    ///
}

- (void)test6 {
    //
    NSLog(@"test6");
}

注:不同协议声明相同方法,在类遵守中实现相同只有一个

相关文章

网友评论

      本文标题:iOS协议

      本文链接:https://www.haomeiwen.com/subject/amarmltx.html