类别:Category
说明,很多时间我只想在一个类上扩展我需要的功能,这个时候,如果只是继承这个类,可能有点大题小作,这个时候我们就引入了类别的概念,类别是OC中特有的
我们创建的时候选择OC-file类型去创建.
注意:类别不能在扩展任何成员变量。
1.声明类别中需要扩展的方法
// MyPoint+ZL.h
// OC
//
// Created by liuking on 16/1/31.
// Copyright © 2016年 liuking. All rights reserved.
//
#import "MyPoint.h"
@interface MyPoint (ZL)
-(void) allSize;
@end
//
// MyPoint+ZL.m
// OC
//
// Created by liuking on 16/1/31.
// Copyright © 2016年 liuking. All rights reserved.
//
#import "MyPoint+ZL.h"
@implementation MyPoint (ZL)
-(void) allSize
{
NSLog(@"我是类别扩展出来的信息");
}
@end
调用刚刚实现的类别
//
// main.m
// OC
//
// Created by liuking on 16/1/31.
// Copyright © 2016年 liuking. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Bar.h"
#import "Foo.h"
#import "MyPoint.h"
#import "PointObserver.h"
#import "MyPoint+ZL.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
MyPoint *point = [[MyPoint alloc] init];
[point allSize];
有时有些方法只想自己看见,而不公开,我们可以使用延展,然后在实现类里实现这个方法
下面这个isMyPoint方法就需要在MyPoint中实现,否则会报警
//
// MyPoint_Extend.h
// OC
//
// Created by liuking on 16/1/31.
// Copyright © 2016年 liuking. All rights reserved.
//
#import "MyPoint.h"
@interface MyPoint () //() 一般不指定名字
-(void) isMyPoint;
@end
需要实现延展里面的方法
//
// MyPoint.m
// OC
//
// Created by liuking on 16/1/31.
// Copyright © 2016年 liuking. All rights reserved.
//
#import "MyPoint.h"
#import "MyPoint_Extend.h"
@implementation MyPoint
@synthesize x;
@synthesize y;
-(void)isMyPoint
{
NSLog(@"我是延展出来的信息。。。。");
}
协议:Protocol
java里面有个接口interface的概念,接口就是一堆方法只是声明,还没有实现。而在OC里面由一个叫协议的protocol来声明一些方法,和java不一同的是,OC可以声音必须现实与选择实现的方法。这和java是不同的
1.使用协议可以使用两个关键字:第一个是@required关键字,该关键字后面的方法必须 实现,如果没有指定@required关键字,协议中所有的方法都是默认必须实现的。
2.协议不能有成员变量
定义一个Protocol
//
// IProtocol.h
// OC
//
// Created by liuking on 16/1/31.
// Copyright © 2016年 liuking. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol IProtocol <NSObject>
@optional //这可是选择实现的方法
-(void) read;
@required //这个是必须实现的方法
-(void) write;
@end
使用协议
//
// ProtocolTest.h
// OC
//
// Created by liuking on 16/1/31.
// Copyright © 2016年 liuking. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "IProtocol.h"
@interface ProtocolTest : NSObject<IProtocol>
@end
//
// ProtocolTest.m
// OC
//
// Created by liuking on 16/1/31.
// Copyright © 2016年 liuking. All rights reserved.
//
#import "ProtocolTest.h"
@implementation ProtocolTest
-(void)write //这个是必须实现的方法
{
NSLog(@"wtrie some things");
}
-(void) read //选择实现的方法
{
NSLog(@"read some things");
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
ProtocolTest *test = [[ProtocolTest alloc] init];
if ([test respondsToSelector:@selector(read)]) { /<span style="color:#ff0000;">/注意这里一定要判断是否有实现read方法,否则会闪退</span>
[test read];
}
[test write];
声明一个必须实现协议的对象,通常需要使用id数据类型,还需要在关键字id后面指定对象要遵守的协议
声明一个实现某协议的变量
id<IProtocol> *delegate;