1.分类创建:
Xcode 6之后 newfile -- Object-C File 选择fileType
2.格式:
@interface 类名 (分类名)
@end
@implementation 类名 (分类名)
@end
在不改变原来类的基础上,可以为类增加方法。
一般为系统类添加分类 或者在大型项目开发时用到。
4.使用注意
1>只能增加方法,不能增加成员变量。
2>分类方法实现中可以访问原来类中声明的成员变量。
3>如果有同名方法,优先级 :分类--->原来类-->父类。
4> 分类可以重新实现原来类的方法,但是会覆盖原来的方法。
5.编译顺序:
看 build phases -- compile sources
Xcode编译.m文件
示例:
给NSString增加类方法分类
+(int)numberCountOfString:(NSString *)string{
int count = 0;//局部变量要初始化
for (int i=0; i<string.length; i++) {
char c = [string characterAtIndex:i];
//注意字符单引号 '' c>=48 && c<=97
if (c>='0'&& c<='9') {
count++;
}
}
return count;
}
给NSString增加对象方法分类
-(int)countNumber{
int count = 0;//局部变量要初始化
for (int i=0; i<self.length; i++) {
char c = [self characterAtIndex:i];
//注意字符单引号 '' c>=48 && c<=97
if (c>='0'&& c<='9') {
count++;
}
}
return count;
}