Objective-c的Categories和protocols
来源:互联网 发布:优化顶碗少年阅读答案 编辑:程序博客网 时间:2024/05/29 10:35
Categories是在不用类继承的前提下扩展已有的类,该扩展将会影响所有的子类,分为两种情况,带名字的和匿名的。
带名字的Category只能用来扩展其方法,不能定义实例变量和属性,如下代码:
//假设Number为已有的类,现对其进行运算扩展
//Number+Ops.h
#import “number.h”
@interface Number(MathOps)
-(Number*) add: (Number*)num;
-(Number*) mul:(Number*) num;
-(Number*) div:(Number*) num;
-(Number*) sub:(Number*) num;
@end
//Number+Ops.m
@implementationNumber (MathOps)
//implementation ofcategory methods
……
@end
匿名的Category是比较特殊的,可以扩展类的实例变量和方法,但所扩展的方法、变量和属性都为private,只能用于类本身,只能扩展存在实现源代码的类。如下代码:
//假设Number为已有的类,并存在其实现部分的源代码,注意文件名称
//file Number_Ext.h
#import “Number.h”
@interface Number() {
int var1;
}
//此属性和方法为private
@property intuniqueID;
-(void) add;
@end
//file Number.m
#import “Number_Ext.h”
@implementationNumber
//已存在的方法实现
…….
//扩展
@syntherizeuniqueID;
-(void) add{
var1 = 2;
self.uniqueID = 2;
}
-(NSString*)description{//override description
[self add];
return @””;
}
@end
Protocols是一系列未实现的方法,其实现延迟到需要该protocol的类,相当于Java中的接口概念,C++中函数成员全为纯虚函数的抽象类。其标识符有@required和@optional,用来表明实现该protocol的类是否必须实现其中的方法。
//定义protocol
@protocol Drawable
@required
-(void) draw;
@optional
-(void)otherAsYouWant;
@end
//实现protocol
@interface Square :NSObject <Drawable>
-(void) draw{}
@end
//实现多个protocol
@interface Square :NSObject <Drawable,Movable>
….
@end
//用法
id <Drawable,Movable>square = [[Square alloc] init];
[square draw];
辉辉
(FightingBull Studio)
- Objective-c的Categories和protocols
- Object-C Categories和Protocols
- Object-C Categories和Protocols
- Object-C Categories和Protocols
- objective-c的categories(分类)
- Objective-C: Categories
- Categories in Objective-C
- Objective-C:Categories
- objective-c protocols详解
- [Objective-C] Categories 小例子
- 一起学Objective-C - Protocols
- object-c的Categories
- Object C的Categories
- Objective-C 中Categories 初体验
- Objective-C categories in static library
- Objective-C categories in static library
- Building Objective-C static libraries with categories
- Building Objective-C static libraries with categories
- 华为中兴在欧更受欢迎 任正非受礼遇
- Ubuntu下面触板的开启、关闭
- 对计算机读研的看法
- 手把手教你学会 Emacs 高级定制
- 莫言教学常启迪学生多动脑 主张把自己当罪人写-莫言-诺贝尔文学奖-兰传斌
- Objective-c的Categories和protocols
- Strategy 模式
- 关于.h,.hh,.hpp,hxx . .cpp,.c,.cc,.cxx 一些小知识
- Android常见游戏引擎及使用实例
- GoAhead Web Server的特性及技术
- adams导出图形数据,并导入matlab进行分析
- 不用/,*,mod乘、除、取模运算的除法
- 中国文联致信祝贺莫言获得诺贝尔文学奖-文联-祝贺-莫言
- Linux 配置文件/配置环境变量