- 概念
- 例子
一、概念
反射:根据字符串实例话对象或者调用方法
// // main.m // 反射机制 // // Created by apple on 14-3-28. // Copyright (c) 2014年 apple. All rights reserved. // #import <Foundation/Foundation.h> #import "Person.h" #import "Student.h" #import "Person.h" #pragma mark NSObject常用方法 void test() { Student *stu = [[[Student alloc] init] autorelease]; // isKindOfClass判断对象是否属于某个类 或者 子类 if ( [stu isKindOfClass:[Person class]] ) { // NSLog(@"stu属于Person或者继承自Person"); } // isMemberOfClass判断对象是否属于某个类(不包括子类) BOOL result = [stu isMemberOfClass:[Student class]]; // NSLog(@"%i", result); // 直接调用 // [stu test]; // 间接调用 [stu performSelector:@selector(test)]; // [stu performSelector:@selector(test2:) withObject:@"abc"]; // 延迟2秒后调用test2:方法 [stu performSelector:@selector(test2:) withObject:@"abc" afterDelay:2]; } //类的反射机制 void test1() { NSString *str = @"Person"; Class class = NSClassFromString(str); Person *person = [[[class alloc] init] autorelease]; NSLog(@"%@", person); NSString *str1 = NSStringFromClass([person class]); NSLog(@"%@", str1); } //方法的反射机制 void test2() { Person *person = [[[Person alloc] init] autorelease]; NSString *str = @"test:"; SEL sel = NSSelectorFromString(str); [person performSelector:sel withObject:@"name"]; NSString *str1 = NSStringFromSelector(sel); NSLog(@"%@",str1); } int main(int argc, const char * argv[]) { @autoreleasepool { test2(); } return 0; }