NSObject 和 反射的使用

//
//  main.m
//  Refect
//
//  Created by Rayln Guan on 9/13/13.
//  Copyright (c) 2013 Rayln Guan. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Student.h"
#import "Person.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        Student *stu = [[Student alloc] init];
        
        //判断Student是否是Person的类或者子类
        BOOL is = [stu isKindOfClass:[Person class]];
        NSLog(@"%i", is);
        //判断Student是否是Person类(不包括子类)
        [stu isMemberOfClass:[Person class]];
        //判断某个类是否实现了某个协议
        //[stu conformsToProtocol:<#(Protocol *)#>]
        
        //判断某个类是否拥有参数提供的方法
        [stu respondsToSelector:@selector(select)];
        
        //间接调用方法
        [stu performSelector:@selector(test1)];
        [stu performSelector:@selector(test2:) withObject:@"abc"];
        //延迟调用
        [stu performSelector:@selector(test2:) withObject:@"abc" afterDelay:2];
        
#pragma mark - reflect
        //类名反射
        NSString *str = @"Person";
        Class class = NSClassFromString(str);
        Person *person = [[class alloc] init];
        
        
        //Class变成字符串
        NSString *name = NSStringFromClass([Person class]);
        
        //方法反射
        NSString *method = @"test1";
        SEL selector = NSSelectorFromString(method);
        [person performSelector:selector];
        
        //将sel转化为字符串
        NSString *method1 = NSStringFromSelector(selector);
        
        [person release];
        
    }
    return 0;
}



Person和 Student只是定义了test1和test2方法而已

你可能感兴趣的:(Objective-C)