IOS学习第五篇——类别(category)

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 ”;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值