Category用法
一、为已有类增加方法;
例如,为NSString类增加新的方法:
//someClass.h
@interface NSString (Capitals)
-(NSString *)alternateCaps:(NSString *)aString;
@end
//someClass.m
@implementation NSString (Capitals)
-(NSString *)alternateCaps:(NSString *)aString
{
// Implementation
}
为类增加的方法可以被子类继承(在子类中添加的方法对父类是不可见的)。
二、对已有类进行扩展;
类的扩展是通过匿名Category来完成的,并且所有方法的实现必须在原类的实现部分完成。
// someClass.m
@interface someClass ()
-(void)extend;
@end
@implementation someClass
// all the methods declared in the .h file and any superclass
// overrides in this block
// Implement private methods in this block as well.
-(void)extend {
// implement private method here;
}
@end
参考:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1
一、为已有类增加方法;
例如,为NSString类增加新的方法:
//someClass.h
@interface NSString (Capitals)
-(NSString *)alternateCaps:(NSString *)aString;
@end
//someClass.m
@implementation NSString (Capitals)
-(NSString *)alternateCaps:(NSString *)aString
{
// Implementation
}
为类增加的方法可以被子类继承(在子类中添加的方法对父类是不可见的)。
二、对已有类进行扩展;
类的扩展是通过匿名Category来完成的,并且所有方法的实现必须在原类的实现部分完成。
// someClass.m
@interface someClass ()
-(void)extend;
@end
@implementation someClass
// all the methods declared in the .h file and any superclass
// overrides in this block
// Implement private methods in this block as well.
-(void)extend {
// implement private method here;
}
@end
参考:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1