[OC Foundationフレームワーク-16]NSObjectと反射

4657 ワード

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 }