[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         //延迟调用,单位sec

6         [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 }

 

 

你可能感兴趣的:(object)