1 分类(扩展)
分类的意思就是扩展某个类,为类添加方法或属性,而且在不改变原来的类的情况下。
应用意义:比如说你要扩展NSArray,NSArray是foundation框架提供的,你无法修改原来的代码,所以提供分类来扩展NSArray。定义如下:
#import <Foundation/Foundation.h>
@interface Student:NSObject
@property int id;
@property NSString* name;
@end
#import "Student.h"
@interface Student (InfoStudent) //分类定义
-(void)printStudent();
@end
//实现
@implementation Student(InfoStudent)
-(void)printStudent(){
NSLog(self.name);
}
@end
这里定义了一个分类,InfoStudent,并提供一个扩展方法printStudent。
注意:不可以添加实例变量。
2 匿名分类
添加分类的时候,括号里不写名字就叫匿名分类,匿名分类里定义的方法需要在主实现区域实现,而不是在分离的实现区域。如下:
#import "Student.h"
@interface Student()
@property int age;
-(void)printStudent();
@end
@implementation Student
@sythesize id,name,age;
-(void)printStudent(){
NSLog(self.name);
}
@end
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">注意:分类添加的扩展对类的子类同样有效;在分类里复写方法不是个好设计。</span>
3 协议
协议与Java里接口的区别就是,协议里的方法可以选择实现。语法如下:
@protocol NSCopying
-(id)copyWithZone:(NSZone*) zone;
@end
//实现
@interface Student:NSObject <NSCopying , NSCodeing>
//方法
@end
@optional 和 @require
@protocol PrintUtil
-(void) print1:(NSStudent*) stu;
@optional
-(void) print2;
-(void) print3;
@end
@optional后面的方法都是可选的,@require是必须实现的方法。
判读是否实现某个协议:conformsToProtocol。
id currentObj;
if( [currentObj conformsToProtocol:@protocol(NSCopying)]==YES )
id<NSCopying , NSCoding> currentObj; //
这个方法可以借助编译器,来提醒currentObj是否遵守NSCopying协议。
扩展协议
@protocol NSCopying <NSCoding>
实现NSCopying的类也需要实现NSCoding。
分类实现协议
@interface Fraction (stuff) <NSCopying>