Objective-C中class、Category、Block的介绍

@class

当定义一个类,必须为编译器提供两组消息,第一组(接口部分.h):构建类的实例的一个基本蓝图。必须指定类名,类的超类,类的实例变量和类型的列表,最后是类的方法的声明。第二组(实现部分.m):实现类的方法的代码。

例如: ------------------------------ RockStar.h -------------------------------------------

#import<Foundation/Foundation.h>//?用#import呢,原因RockStar继承NSObject类,需要知道NSObject的方法属性等,所以用#import。

@class Banid;//这里为什么没用#import “Banid”,导入包是把所有的信息导入,这个效率比较低,而@class只是说明Banid是一个类,在实现部分在导入包(import),效率高

@interface RockStar:NSObjtect

@end

-------------------------------- RockStar.m------------------------------------------------------------

#import ”RockStar.h”

#import “Banid.h”

@implementation RockStar

@end

Category分类有三个使用场景:定义一个类时某些情况系(需求变更),需要添加新的方法2、团队合作方法的实现3、对基础类库中的方法的扩充,例如NSString+JSON.h为NSString这个类拓展一些解析JSON的方法

@interface Student(Text)//这是一个分类,是对Student类的拓展,对Stduent方法属性等的补充。

@end

Protocal(协议说就是一系列方法的列表,其中声明的方法可以被任何类实现,这种模式一般称为代理(delegation0式,相当于java中的接口,但是协议中的方法可以部分实现,不需要全部

------------------------------TabelPrinter.h-----------------

@protocal TablePrintDataSource

@required//必需的,默认是必须的,也就是使用的类必须实现所有的方法(但也不强求也就是说你不实现编译器也可以通过,再次强调OC是一种弱语言)

-(NSString*)stringForRowAtIndex: (int)index;

-(int) numberOfRowsInTable;

@optionl//可选的

-(NSString*) tableTitle;

-(BOOL) printLineNumber;

@end

@interface TablePrinter:NSObject

@property(nonatomic,assign)id<TablePrintDataSource> datasource;//这里弱引

-(void)printable;

@end

在另一个类中使用时在.h中添加@protocal TablePrintDataSource ;在.m中添加

#import “Table”

或者协议可以单独写出来:项目中有,别的地方用时在.h中添加@protocal TablePrintDataSource ;在.m中添加#import“TablePrintDataSource.h”

Block

Block可以访问外面定义的变量,__block int c=20,这样可以外部写该外部变量,否则不可以修改,只可以使用

例子1、

int j=10;

int (^blockPtr)(int)=^(int n){return j+n}; //带一个参数返回值为int的块,块是基于栈的,块与自动变量拥有相同的生命周期。(^)脱字符

j=20;

int k=blockPtr(5);//k is 15,not 25

例子2、

Void someFunction(int (^blockArg)(int));

Int (^doubler) (int)=^(int n){return n*2};

someFunction(doubler);

例子3、

void someFunction(int (^blockArg)(int));

someFunction(^(int n){ return n*2;});

例子4、

Void text()

{

Typedef int (^Sum)(int,int);

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