很多人給工程調試時,每個界面都寫dealloc,能達到效果,未免有些麻煩。下面介紹一個小小實例:
控制器寫個分類,用runtime方法交換。
一、控制器、View分類
1.新建分類
#import "UIViewController+XYController.h"
2.m引入頭文件
#import <objc/runtime.h>
3.實現如下兩個方法
+ (void)load{
Method m1 = class_getInstanceMethod([self class], NSSelectorFromString(@
"dealloc"));
Method m2 = class_getInstanceMethod([self class], @selector(xy_dealloc));
method_exchangeImplementations(m1, m2);
}
- (void)xy_dealloc
{
NSLog(@"xy_dealloc - %@",[self class]);
[self xy_dealloc];
}
二、字體適配也可交換方法
+ (void)load
{
Method m1 = class_getClassMethod(self, @selector(systemFontOfSize:));
Method m2 = class_getClassMethod(self, @selector(MDJ_ystemFontOfSize:));
method_exchangeImplementations(m1, m2);
}
+ (void)MDJ_ystemFontOfSize:(CGFloat)fontSize
{
MDJLog(@"----");
// 以iPhone6屏幕對角線爲基準,計算不同機型的比例,根據項目可以適當調整比例。
if (Iphone5){
fontSize -=1;
}else if (Iphone6Plus){
fontSize +=1;
}
[self MDJ_ystemFontOfSize:fontSize];
}
三、給NSObject寫分類,調試打印整齊,易於查看
#import "NSObject+MDJExtnestion.h"
#import <objc/message.h>
@implementation NSObject (MDJExtnestion)
#define MYTest2
#ifdef MYTest
- (NSString *)description
{
NSMutableString *descri = [NSMutableString string];
unsigned int count = 0;
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; i ++) {
objc_property_t property = properties[i];
const char *cProperty = property_getName(property);
id ocProperty = [NSString stringWithUTF8String:cProperty];
id value = [self valueForKey:ocProperty];
[descri appendFormat:@" %@ : %@ ",ocProperty,value];
}
return descri;
}
#endif
@end