黑马程序员--IOS_学习笔记_block和@protocol

来源:互联网 发布:淘宝网短款连帽棉服 编辑:程序博客网 时间:2024/05/19 13:13


------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------


一、Block代码块

1、block  是OC中的一种数据类型,也是代码块,和函数相似。也有参数,返回值。通过  ^  关键字定义。

1> 在block内部可以访问局部变量。

2> 但是默认不能修改,如果想要修改局部变量,可以在局部变量前加上__block 关键字。

3> 通过typedef可以其简写block数据类型。


2、示例

1.定义一个block返回就两个int类型的和。

int (^SumBlock)(int,int) = ^(int a,int b){return a + b;}; 

2.定义一个block返回两个int类型的差。

int (^MinusBlock)(int,int) = ^(int a,int b){return a - b;};


3、通过typedef给方法设置别名

typedef int (^MyBlock) (int,int);

MyBlock sumblock = ^(int a,int b){return a + b;};

MyBlock minusblock = ^(int a, int b) {return a-b;};


二、协议

1、@Protocol  协议  

知识点:协议里面包含方法的声明,遵守协议的类必须实现必须实现的类。


2、示例:

1. @protocol FlyProtocol <NSObject> // 所有的协议都遵守基本协议 

@required  // 必须的,遵守协议的类必须实现。

- (void)Fly;

@optional  // 可选的 ,可以不实现

- (float) Speed;

@end // FlyProtocol 


2. @class  Animal。// 告诉编译器后面的是一个类,只需要知道那是一个类就可以了,在实现部分在导入所有的类的内容。提高性能。

@protocol FlyProtocol;  // 告诉编译器,后面的时候一个协议,在类的实现部分在包含协议的所有内容。

@interface Bird : Animal <FlyProtocol>  // 类鸟 遵守协议 FlyProtocol

@property (nonatomic, strong, readwrite) id<otherprotocol> objprotocol;  // 必须是遵守了 otherprotocol 协议的对象。

@end // Bird 


3.#import "Animal.h" // 这里导入类的所有实现。

#import "FlyProtocol.h" // 这里在导入所有的协议的内容。

@implementation Bird

- (void) Fly

{

  NSLog(@"飞。");

}

@end // Bird


知识点:类只能带继承,协议可以遵守多个,通过,  <protocol1,protocol2>

               Animal<FlyProtocol> *a = [[Bird alloc] init];  // 鸟 类 必须继承,Animal类,必须遵守 FlyProtocol协议。  可以对要赋值的对象进行限制。



0 0