A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© qiang0901 中级黑马   /  2015-5-4 14:27  /  1091 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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];//打击了按钮 被通知

}

}


运行结果:

我被打击了

1 个回复

倒序浏览
13673696542 来自手机 中级黑马 2015-5-4 21:19:17
沙发
咋啦,你没用xcode么?
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马