美文网首页
OC中的反射机制

OC中的反射机制

作者: 小凡凡520 | 来源:发表于2018-11-26 15:35 被阅读2次

    不能将 swift 中的自定义类进行反射,系统的类可以

    class反射
    • 过类名的字符串形式实例化对象
    // swift
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        if let clasName = NSClassFromString("Person") as? Person.Type {
            let person = clasName.init()
            
            print(person)
        }
    }
    
    // OC
    Class class = NSClassFromString(@"Person");
    Student *stu = [[class alloc] init];
    
    // 输出:
    <Person: 0x600000012800>
    
    • 类名变为字符串
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let name = NSStringFromClass(Person.classForCoder())
        print(name)
    }
    
    // 输出
    <Person: 0x60400001c8b0>
    Person
    
    SEL的反射
    • 通过方法的字符串形式实例化方法
    - (void)setName {
        NSLog(@"test");
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        if let clasName = NSClassFromString("Person") as? Person.Type {
            let person = clasName.init()
            
            let sel = NSSelectorFromString("setName")
            
            person.perform(sel)
        }
    }
    
    // 输出
    2018-11-26 15:31:45.972108+0800 Demo[5981:625183] test
    
    • 将方法变成字符串
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        if let clasName = NSClassFromString("Person") as? Person.Type {
            let person = clasName.init()
            
            let sel = NSSelectorFromString("setName")
            
            person.perform(sel)
            
            let className = NSStringFromSelector(sel)
            print(clasName)
        }
    }
    

    相关文章

      网友评论

          本文标题:OC中的反射机制

          本文链接:https://www.haomeiwen.com/subject/grfudftx.html