替換已有方法的實現:
- 在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] 分類中的方法二