Person.h
#import <Foundation/Foundation.h> @interface Person : NSObject -(void)eat; @end //2.第二种方法 //分类的声明 //创建分类@interface <#class name#> (<#category name#>) @interface Person (MyCategory) -(void)run; @end
Person.m
#import "Person.h" @implementation Person -(void)eat{ NSLog(@"%@:eat",[self class]); } @end //分类的实现 @implementation Person (MyCategory) -(void)run{ NSLog(@"%@:run",[self class]); } @end
Teacher.h
#import "Person.h" @interface Teacher : Person -(void)study; @end
Teacher.m
#import "Teacher.h" @implementation Teacher -(void)study{ NSLog(@"%@ :study",[self class]); } //重写父类方法 -(void)eat{ [super eat];//保存父类方法 NSLog(@"teacher not eat"); } @end
Person+Category.h
#import "Person.h" //1.第一种方法 //系统文件创建分类 //创建分类@interface Person (Category分类名可省略) @interface Person (Category) -(void)play; @end
Person+Category.m
#import "Person+Category.h" @implementation Person (Category) -(void)play{ NSLog(@"%@ play",[self class]); } @end
Person_MyExtension.h
#import "Person.h" //与分类的区别 //@interface <#class name#> (<#category name#>) //@end @interface Person () @end
main.m
#import <Foundation/Foundation.h> #import "Person.h" #import "Teacher.h" #import "Person+Category.h" int main(int argc, const char * argv[]) { @autoreleasepool { Person*person=[[Person alloc]init]; [person eat]; [person play]; [person run]; Teacher*teacher=[[Teacher alloc]init]; [teacher eat]; [teacher study]; [teacher play]; [teacher run]; } return 0; }
时间: 2024-10-28 10:43:35