分类
//原始类
#import <Foundation/Foundation.h>
@interface Category : NSObject
@property (nonatomic ,retain) NSString *test;
- (void)thisIsANowClassMethod;
@end
#import "Category.h"
@implementation Category
- (void)thisIsANowClassMethod
{
NSLog(@"This is a now Class method");
}
@end
//分类的接口部分
#import "Category.h"
@interface Category (Child)
- (void)thisIsACategoryMethod;
@end
/*分类:
分类提供了一种简单地方式,将类定义模块化到相关方法的组中
它是对现有类定义的一种扩展
注意:
1、分类可以访问原始类的实例变量,但是能添加自身的任何变量。
2、分类可以重载原始类的方法,(这种做法比较拙劣:重载了一个方法后,再也不能访问原来的方法,因此必须将重载方法的所有功能复制到替换方法中(但是在子类中重载方法任然可以使用super来引用父类的方法))
3、分类的实现中不必实现在分类接口部分声明的全部方法,可以再你使用得时候再实现
4、一个原始类可以拥有很多分类
5、通过分类添加新方法来扩展一个类不仅会影响原始类,还会影响原始类的所有子类
6、对象分类名必须是唯一的*/
//分类的实现部分
#import "Category+Child.h"
@implementation Category (Child)
- (void)thisIsACategoryMethod
{
NSLog(@"This is a Category Method");
}
@end
//这点也需要注意:在其他类引入头文件时如果只是引入原始类的头文件#import "Category.h",则只能使用原始类中的成员变量和方法,但是如果引入#import "Category+Child.h"就可以使用原始类和其分类中的所有方法
优质内容筛选与推荐>>