iOS 设计模式 之 category
category模式是用于向已经存在的类添加方法,达到扩展该类的目的。继承于该类的子类也会有扩展后的方法。当知道某一个类的某一个方法有bug时,而这个类又是在库当中,无法修改,就通过category 写一个方法代替原来类中的bug方法,而又不会影响原来方法的使用。category不能向被扩展类添加实例变量。
1.category的作用
(1).在不创建继承类的情况下,对已有类的扩展。
(2).简化类的开发.当多个人要开发同一个类时,就需要用category模式,便于他们独立开发。
(3).没有源代码的情况下修改bug
2.category的使用(例如)
(1).建一个类, -> NSString (取名为:BothNSString)
(2).在BothNSString.h文件中 实现 category
@interface NSString (BothNSString)
+(NSString *) getBothString:(NSString *)str;
@end;
(3)在 BothNSString.m文件中
@implementation NSString (BothNSString)
+(NSString *)getBothString:(NSString *)str{
NString returnString = @"";
returnString = [str stringByAppendingString:str];
return returnString;
}
@end;
(4).在任意文件中用该方法。
#import "BothNSString.h"
NSString str = @"qwe";
str = [NSString getBothString:str];//此时调用了BothNSString中getBothString方法,str已经变成了 “ qweqwe ”;