//类别的作用:在已有的类中添加方法
Demo:新建文件在NSString类中添加一个打印自身的方法, 直接在main文件中声明和实现NSArray打印自身的方法
//
// main.m
// 类别
//
// Created by Macro on 14-12-7.
// Copyright (c) 2014年 Macro. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "NSString+SelfPrint.h"
// 类别只使用在本文件中,则无需interface
@interface NSArray (show)
- (void)show;
@end
@implementation NSArray (show)
- (void) show
{
for (id obj in self) {
NSLog(@"%@", obj);
}
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
[@"Hello" selfPrint];
NSMutableString *str = [[NSMutableString alloc] initWithString:@"HelloWorld"];
[str selfPrint];
[[str reversal] selfPrint];
[str release];
[@[@"中国", @"中华"] show];
}
return 0;
}
//
// NSString+SelfPrint.h
// 类别
//
// Created by Macro on 14-12-7.
// Copyright (c) 2014年 Macro. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSString (SelfPrint)
//这是类别 在类别中声明方法,就如同声明在原类中
//当前类是NNString
//类别中不能声明成员变量
- (void) selfPrint;
- (NSString *)reversal;
@end
//
// NSString+SelfPrint.m
// 类别
//
// Created by Macro on 14-12-7.
// Copyright (c) 2014年 Macro. All rights reserved.
//
#import "NSString+SelfPrint.h"
@implementation NSString (SelfPrint)
- (void) selfPrint
{
//类别中的对象方法,一样可以使用原类的成员变量
//不能使用声明在.m文件中的变量
NSLog(@"%@", self);
}
- (NSString *)reversal
{
NSMutableString * str = [[NSMutableString alloc] init];
for (NSInteger i = [self length] - 1; i >= 0; i--) {
[str appendFormat:@"%C", [self characterAtIndex:i]];
}
return [str autorelease];
}
@end