用Category来扩展一个类

想要给一个类添加方法和行为,但不想创建一个全新的子类。

在Objective-C中,可以用categories来定义并实现属性和方法,之后再将它们附加到一个类上。

假设你想要扩展NSString类,给它加一些方法来帮助你创建HTML文本。那么这个category头文件就会看起来像这样:

@interface NSString (HTMLTags)

在@interface关键字后的类名就是正要扩展的类。这意味着此category可能只能被运用到NSString或NSString的子类。类名后的括号中的HTMLTags就是category的名字。

The implementation follows a similar pattern.

@implementation NSString (HTMLTags)

以后要用时,导入category的头文件就可以了。

The Code
Listing 1-13. HTMLTags.h
#import <Foundation/Foundation.h>
 
@interface NSString (HTMLTags)
 
-(NSString *) encloseWithParagraphTags;
 
@end

Listing 1-14. HTMLTags.m
#import "HTMLTags.h"
 
@implementation NSString (HTMLTags)
 
-(NSString *) encloseWithParagraphTags{
        return [NSString stringWithFormat:@"<p>%@</p>",self];
}
 
@end

Listing 1-15. main.m
#import "HTMLTags.h"
 
int main (int argc, const char * argv[]){
        @autoreleasepool {
                NSString *webText = @"This is the first line of my blog post";
 
                //Print out the string like normal:
                NSLog(@"%@", webText);
 
                //Print out the string using the category function:
                NSLog(@"%@", [webText encloseWithParagraphTags]);
        }
        return 0;
}

猜你喜欢

转载自zsjg13.iteye.com/blog/2258977