/******** 第七章 类的扩展: 类目Category, 延展Extension, 协议Protocol ( 一 ) ********/
// 一、Category(类目, 类别, 分类等等):
// 给不知道源码的类添加方法
/* 添加的方法的声明, 会成为本类的一部分, 能够被子类继承
常用于给系统类添加方法,不能添加实例变量
=====================================================
1.新建文件 command + n
2.选择Object-c File模板
3.File栏根据扩展的功能写入文件名
4.中间栏选择Category
5.Class选项写入对那个类的扩充,就写入那个类的类名
6.next之后会自动生成一对“类名 + 扩展名.h”和“类型加扩展名.m”文件
7.在.h写入方法声明,在.m中写方法实现
*/
@interface NSString (sayHi)
{
NSInteger _age ; error!!!不能添加实例变量, 只能添加方法
}
@end
====================================================
// 练习1: 使用Category为 NSString类 添加一个类方法, 实现去除字符串中的数字
NSString *str = @"sdadsa213";
[str sayHi];
NSLog(@"str字符串中数字的个数:%ld",[str numberCount]);
// .m文件:
@implementation NSString (sayHi)
-(NSInteger)numberCount{
NSInteger count = 0;
for (int i = 0; i < self.length; i++) {
if ([self characterAtIndex:i] >= '0' && [self characterAtIndex:i] <= '9') {
count++;
};
}
return count;
}
@end
// 练习2: 使⽤Category为NSDate类添加一个类⽅方法(dateWithDateString:),实现将下述字符串转换为NSDate对象。
// 将@“20140402142850”转换为NSDate
NSString *dateStr = @"20140402142850";
NSDate *date2 = [NSDate nsdateFromStr:dateStr];
NSLog(@"%@",date2);
// .m文件:
@implementation NSDate (dataWithDateString)
+(NSDate *)nsdateFromStr:(NSString *)str{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
return [dateFormatter dateFromString:str];
}
@end
====================================================
//二、延展Extension:
// 管理私有方法以及私有实例变量, 只在该类内部调用的方法
/***** 不需要创建.h文件,直接将延展写到类的.m文件中, 只适合能看到源文件的类 *****/
// 给Student添加延展:
@interface Student()
{
NSString *_hobby;
}
- (void)test;
@end
@implementation Student
-(int)random{
int random = arc4random() % (10 - 1 + 1) + 1;
return random;
}
- (void)test1{
[self test];
int random = [self random];
}
- (void)test{ //延展的声明
_hobby = @"hahaha";
NSLog(@"%@",_hobby);
}
- (void)sayHello{
NSLog(@"Hello");
[self test];//调用延展里面声明的方法
}
@end
====================================================
/* 总结: 延展和类目的区别
1.延展中可以添加实例变量,类目中不可以
2.延展中的方法和实例变量都是私有的,不能直接访问,类目中的方法外界可以访问
3.延展针对是已知类(因为它的实现只能在这个类的.m文件中写),类目中可以为不知道源文件的类添加方法;
4.延展中的子类不能继承,而类目中的方法子类可以直接使用
*/
OC - 第七章 类的扩展: 类目Category, 延展Extension, 协议Protocol ( 一 )
最新推荐文章于 2016-08-16 22:56:46 发布