分类的总结
2015-09-16 17:12
411 查看
分类(category)是在不修改原有的类的基础上增加新的方法。
使用步骤是:声明分类-实现分类-使用分类
一般来说分类的命名规则为:类名+扩展方法(即分类名称)
分类不继承父类,但会被子类继承。
分类的注意事项有:
1.分类只能增加方法,不能增加成员变量,不能使用@property
2.在分类中存在和类同名的方法,则优先使用分类的方法
3.如果多个分类都与类同名,则执行的是最后编译的文件方法。
分类的格式为:
@interface 待扩展的类名 (分类的名称)
@end
例如:
@ interface Person (base)
-(void) run;
-(void) eat;
@end
具体使用方法为:
#import <Foundation/Foundation.h>
//头文件命名惯例:ClassName+CategoryName.h
@interface NSString (CamelCase)
-(NSString*) camelCaseString;
@end
@implementation NSString (CamelCase)
-(NSString*) camelCaseString
{
//调用NSString的内部方法获取驼峰字符串。
//self指向被添加分类的类。
NSString *castr = [self capitalizedString];
//创建数组来过滤掉空格, 通过分隔符对字符进行组合。
NSArray *array = [castr componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
//把数组的字符输出
NSString *output = @"";
for(NSString *word in array)
{
output = [output stringByAppendingString:word];
}
return output;
}
@end
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *str = @"My name is bill.";
NSLog(@"%@", str);
str = [str camelCaseString];
NSLog(@"%@", str);
[pool drain];
return 0;
}
使用步骤是:声明分类-实现分类-使用分类
一般来说分类的命名规则为:类名+扩展方法(即分类名称)
分类不继承父类,但会被子类继承。
分类的注意事项有:
1.分类只能增加方法,不能增加成员变量,不能使用@property
2.在分类中存在和类同名的方法,则优先使用分类的方法
3.如果多个分类都与类同名,则执行的是最后编译的文件方法。
分类的格式为:
@interface 待扩展的类名 (分类的名称)
@end
例如:
@ interface Person (base)
-(void) run;
-(void) eat;
@end
具体使用方法为:
#import <Foundation/Foundation.h>
//头文件命名惯例:ClassName+CategoryName.h
@interface NSString (CamelCase)
-(NSString*) camelCaseString;
@end
@implementation NSString (CamelCase)
-(NSString*) camelCaseString
{
//调用NSString的内部方法获取驼峰字符串。
//self指向被添加分类的类。
NSString *castr = [self capitalizedString];
//创建数组来过滤掉空格, 通过分隔符对字符进行组合。
NSArray *array = [castr componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
//把数组的字符输出
NSString *output = @"";
for(NSString *word in array)
{
output = [output stringByAppendingString:word];
}
return output;
}
@end
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *str = @"My name is bill.";
NSLog(@"%@", str);
str = [str camelCaseString];
NSLog(@"%@", str);
[pool drain];
return 0;
}
相关文章推荐
- nodejs实现获取某宝商品分类
- php通过分类列表产生分类树数组的方法
- asp飞飞无限级分类v1.0 Asp+sql+存储过程+ajax提供下载
- Oracle表的分类以及相关参数的详解
- Objective-C的内省(Introspection)用法小结
- php+mysql实现无限分类实例详解
- Objective-C中常用的结构体NSRange,NSPoint,NSSize(CGSize),NSRect实例分析
- Objective-C中NSLog输出格式大全
- Swift调用Objective-C编写的API实例
- Swift、Objective-C、Cocoa混合编程设置指南
- Objective-c代码如何移植为Swift代码 Objective-c代码转移到Swift过程介绍
- Swift调用Objective-C代码
- 以实例讲解Objective-C中的KVO与KVC机制
- objective-c中生成随机数的方法
- 在Swift中使用Objective-C编写类、继承Objective-C类
- Swift能代替Objective-C吗?
- Objective-C 消息传递机制详解
- 在一个项目中同时使用Swift和Objective-C代码混合编程的方法
- vm安装mac os x 10.7 lion