替换已有方法的实现:
- 在Category中实现原类中已有的方法后,会覆盖原方法。
- 只需要将Category文件添加进工程即可,不需要import导入也会生效。
- 在Category头文件中不需要再次声明原类中已有的方法。
- 即便是在原类中使用self调用方法,也会只执行Category中的方法。
示例:
TestAbc.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface TestAbc : NSObject
+ (void)leifangfa;
- (void)fangfayi;
- (void)fangfaer;
@end
NS_ASSUME_NONNULL_END
TestAbc.m
#import "TestAbc.h"
@implementation TestAbc
+ (void)leifangfa {
NSLog(@"类文件中的类方法");
}
- (void)fangfayi {
NSLog(@"类文件中的方法一");
[self fangfaer];
}
- (void)fangfaer {
NSLog(@"类文件中的方法二");
}
@end
TestAbc+cate.h
#import "TestAbc.h"
NS_ASSUME_NONNULL_BEGIN
@interface TestAbc (cate)
@end
NS_ASSUME_NONNULL_END
TestAbc+cate.m
#import "TestAbc+cate.h"
@implementation TestAbc (cate)
+ (void)leifangfa {
NSLog(@"分类中的类方法");
}
- (void)fangfaer {
NSLog(@"分类中的方法二");
}
@end
执行:
ViewController.m
#import "ViewController.h"
#import "TestAbc.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[TestAbc leifangfa];
[[TestAbc new] fangfayi];
}
@end
执行结果:
2019-07-25 22:53:50.288454+0800 testProj[1259:48531] 分类中的类方法
2019-07-25 22:53:50.288594+0800 testProj[1259:48531] 类文件中的方法一
2019-07-25 22:53:50.288701+0800 testProj[1259:48531] 分类中的方法二