黑马程序员——category和protocol协议

category的使用
 
给类动态的 添加一些新的方法  可以保证原有的类的数据不变 功能增加时再加以扩展
 
这样就不需创建子类 用最简单的方式实现类的方法 模块化 把不同的类方法支配到分类 文件里
 
例:
 
 #import <Founation\Founation.h> //创建一个类
 
@interface Student:NSObject
-(void)study;
 
@end
 
#import "Student.h"
 
@implementation Student
-(void)study{
NSLog(@"hard study ");
 
}
 
 
 
 
@synthesize age=_age;
 
@end
 
//为Student类动态的添加新方法
 
 
 #import "Student.h" // 导入student.h .不能使用@class 以防止扩充后的方法名与被扩充的类方法名重复
                     
 
@interface Student (Test)
 
-(void)sport;
@end
 
 
#import "Student+Test.h"
 
@implementation
 
-(void)sport{
 
NSLog(@"basketball and football");
 
 
}
 
 
@end
 
 
#import "Student.m"
 
#import "Student+Test.m" //要导入分类方法的.h文件
 
void main(){
 
@aotoreleasepool{
Student *stu=[[[Student alloc] init] autorelease];
 
[stu study];
 
[stu sport];//成功的调用了扩充的方法
 
}
 
}
 
打印结果:
 
hard studey
 
basketball and football
 
 
使用场景 : 当 一个项目 需求变更 时又不想改变原始 类的架构  项目规模大时 使用分类更有效的维护和管理
 
 
@protocol 的使用
 
就是代理 模式  一系列方法的列表 其中声明的方法可以被实任何类所实现 
 
 
 
#import <Foundation/Foundation.h> 
 
@class Button;   
 
@protocol ButtonDelegate <NSObject> //定义一个协议 并遵守了NSObject协议
 
-(void)onClick:(Button *) btn;//实现协议 中的方法
 
@end
@interface Button:NSObject 
 
@property(nonatomic,retain) id<ButtonDelegate> delege; //被代理类
 
-(void)click; //打击按钮 通知自己被点击了
 
@end
 
 
 
 
 
#import "Button.h"
 
@implementation Button
 
-(void)click{
 
[_delegate onClick:self];
 
}
 
 
-(void)dealloc{
[_delegate release];
[super dealloc];
 
}
 
@end
 
 
// 进来的用户
#import <Foundation/Foundation.h>
 
@protocol ButtonDelegate;
 
@interface myLinter :NSObject<ButtonDelegate>
//用户遵守协议
 
@end
 
 
 
#import "myLinter.h"
 
#import "Button.h"
 
@implementation  myLinter //实现了协议
 
-(void)onClick:(Button *)btn{
 
NSLog(@"我被打击了 %@",btn);//点击了按钮
 
}
@end   
 
 
 #import <Foundation/Foundation.h>
 #import "Bootton.m"
 #import "myLinter.m"
 
void main(){
 
@autoreleasepool{
Button *button=[[[Button alloc] init] autorelease];
 
myLinter *lin=[[[myLinter alloc] init] autorelease];
 
[button onClik:button];//打击了按钮 被通知
 
}
 
}
 
 
运行结果:
 
我被打击了
posted @ 2015-04-30 20:07  强子0901  阅读(158)  评论(0编辑  收藏  举报