1.動(dòng)態(tài)獲得類(lèi)的所有屬性
注:需要導(dǎo)入頭文件:#import <objc/runtime.h>
+ (NSArray *)getAllProperties {
NSMutableArray *arrM = [NSMutableArray array];
unsigned int count = 0;
// 獲得指定類(lèi)的所有屬性
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (int index = 0; index < count; ++index) {
// 對(duì)應(yīng)的屬性
objc_property_t property = properties[index];
const char *name = property_getName(property);
// C語(yǔ)言轉(zhuǎn)OC
NSString *ocName = [[NSString alloc] initWithCString:name encoding:NSUTF8StringEncoding];
[arrM addObject:ocName];
}
return arrM;
}
2.動(dòng)態(tài)的遍歷一個(gè)類(lèi)的所有成員變量
- (void)viewDidLoad {
[super viewDidLoad];
unsigned int count = 0;
/** Ivar:表示成員變量類(lèi)型 */
Ivar *ivars = class_copyIvarList([BDPerson class], &count);//獲得一個(gè)指向該類(lèi)成員變量的指針
for (int i =0; i < count; i ++) {
//獲得Ivar
Ivar ivar = ivars[i]; //根據(jù)ivar獲得其成員變量的名稱(chēng)--->C語(yǔ)言的字符串
const char *name = ivar_getName(ivar);
NSString *key = [NSString stringWithUTF8String:name];
NSLog(@"%d----%@",i,key);
}
}
3.為分類(lèi)添加屬性
使用objc_setAssociatedObject方法給分類(lèi)添加屬性
const char *XYKey = "XYKey";
- (void)setName:(NSString *)name {
// @param object#> 某個(gè)象添加屬性
// @param key#> 保存屬性值使用key
// @param value#> 屬性的值
// @param policy#> 屬性修飾詞
objc_setAssociatedObject(self, XYKey, name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)name {
return objc_getAssociatedObject(self, XYKey);
}
4.動(dòng)態(tài)交換兩個(gè)方法的實(shí)現(xiàn)
可使用runtime的交互方法,給系統(tǒng)的方法添加功能. 實(shí)現(xiàn) : 添加一個(gè)分類(lèi) --> 在分類(lèi)中提供一個(gè)需要添加的功能的方法 --> 將這個(gè)方法的實(shí)現(xiàn)和系統(tǒng)自帶的方法的實(shí)現(xiàn)交互.
#import <UIKit/UIKit.h>
@interface UIImage (XYImage)
+ (UIImage *)xy_imageName:(NSString *)imageName;
@end
在.m文件中
#import "UIImage+XYImage.h"
#import <objc/runtime.h>
@implementation UIImage (XYImage)
+ (void)load {
Method imageNameMethod = class_getClassMethod(self, @selector(imageNamed:));
Method xy_imageNameMethod = class_getClassMethod(self, @selector(xy_imageName:));
// 交換方法的地址
method_exchangeImplementations(imageNameMethod, xy_imageNameMethod);
}
+ (UIImage *)xy_imageName:(NSString *)imageName {
UIImage *image = [UIImage xy_imageName:imageName];
if (!image) {
NSLog(@"圖片不存在");
}
return image;
}
使用:(會(huì)打印出圖片不存在)
#import "ViewController.h"
#import "UIImage+XYImage.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[UIImage imageNamed:@"abc.png"];
}