首页 > 代码库 > [OC Foundation框架 - 16] NSObject和反射

[OC Foundation框架 - 16] NSObject和反射

1.判断某个对象是否属于一个类

1         Student *stu = [[[Student alloc] init] autorelease];2         BOOL result= [stu isKindOfClass:[Person class]];3         NSLog(@"%i", result);4        5         //判断对象是否属于某个类,不包括子类6         NSLog(@"%i",[stu isMemberOfClass:[Student class]]);7         NSLog(@"%i",[stu isMemberOfClass:[Person class]]);
 
2.间接调用对象的一个方法
1         //间接调用2         [stu performSelector:@selector(test)];3         [stu performSelector:@selector(test2:) withObject:@"ABC"];4        5         //延迟调用,单位sec6         [stu performSelector:@selector(test2:) withObject:@"yuoo" afterDelay:2];
 
3.类名反射,方法反射
 1 void reflect() 2 { 3     //类的反射 4     NSString *str = @"Person"; 5     Class class = NSClassFromString(str); 6     7     Person *p = [[class alloc] init]; 8     NSLog(@"%@", p); 9    10     NSString *str2 =  NSStringFromClass([Person class]);11    12     //方法的反射13     NSString *method = @"test";14     SEL selector = NSSelectorFromString(method);15     NSLog(@"reflect method:");16     [p performSelector:selector];17 }

 

 

[OC Foundation框架 - 16] NSObject和反射