iOS 类和函数的映射
2025-03-16 本文已影响0人
lukyy
使用场景:数据解析、动态调用
- (void)test {
/*
* 一).类的映射
*/
// 1.通过字符串获取类
NSString *className = @"Student"; // MyClass
Class targetClass = NSClassFromString(className);
if (targetClass) {
// 2. 创建类的实例
// 3. 设置属性
id instance = [[targetClass alloc] init];
[instance setValue:@"John" forKey:@"name"];
[instance setValue:@30 forKey:@"age"];
// 4. 调用方法
if ([instance respondsToSelector:@selector(printInfo)]) {
[instance performSelector:@selector(printInfo)];
} else {
NSLog(@"方法 printInfo 不存在");
}
} else {
NSLog(@"类 %@ 不存在", className);
}
/*
* 二).SEL的映射
*/
// 创建类的实例
MyClass *myInstance = [[MyClass alloc] init];
// 1.通过字符串映射 SEL
// 2.检查方法是否存在
// 3.调用无参数方法
NSString *methodName1 = @"printHello";
SEL selector1 = NSSelectorFromString(methodName1);
if ([myInstance respondsToSelector:selector1]) {
[myInstance performSelector:selector1];
} else {
NSLog(@"方法 %@ 不存在", methodName1);
}
// 调用带一个参数的方法
NSString *methodName2 = @"printMessage:";
SEL selector2 = NSSelectorFromString(methodName2);
if ([myInstance respondsToSelector:selector2]) {
// 使用 performSelector:withObject: 调用带一个参数的方法
[myInstance performSelector:selector2 withObject:@"带一个参数"];
} else {
NSLog(@"方法 %@ 不存在", methodName2);
}
}