【Swift】如何动态选择类以及类方法

Swift版本:swift 5

根据类名选择对应的类,根据方法名选择类中的方法

新建工程FindCassFromStringName,在工程中新建一个类NewClass.swift

将NewClass.swift类更改如下:

import Cocoa

class NewClass: NSObject {
    
    @objc func testFunction() {
       print("this is a new class")
    }
    
    @objc func testFunction2(_ parameter:String) {
       print("this is a new class, parameter:", parameter)
    }
    
    @objc func testFunction3() -> String {
       return "Hello World!"
    }
}

将AppDelegate.swift类更改如下:


import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        
        
        //类的名称
        let className = "NewClass"
        //根据"APP名称.类名称"查找对应的类
        let nsObjc = NSClassFromString(getAPPName() + "." + className) as! NSObject.Type
        //初始化类
        let objc = nsObjc.init()
        
        /* ******* 不需要传递参数,只执行类中的方法 ******* */
        
        // 将初始测试数据传递给测试类的testFunction方法
        let sel1 = NSSelectorFromString("testFunction")
        //判断类中的方法是否存在
        if (objc.responds(to: sel1)) {
            //执行类方法
            objc.perform(sel1)
        }
        
        /* ******* 传递参数,执行类中的方法 ******* */
        let sel2 = NSSelectorFromString("testFunction2:")
        //判断类中的方法是否存在
        if (objc.responds(to: sel2)) {
            //执行类方法
            objc.perform(sel2, with: "Hello World!")
        }
        
        /* ******* 执行类中的方法, 获取返回值 ******* */
        let sel3 = NSSelectorFromString("testFunction3")
        //判断类中的方法是否存在
        if (objc.responds(to: sel3)) {
            //执行类方法
           let resp:String = objc.perform(sel3).takeUnretainedValue() as! String
            print("return value:", resp)
        }
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }
    
    func getAPPName() -> String {
        guard var appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String else { return "" }
       //如果工程名字中带有“-” 符号  需要加上 replacingOccurrences(of: "-", with: "_") 这句代码把“-” 替换掉  不然会报错, 要不然系统会自动替换掉 这样就不是你原来的包名了
        if appName.contains("-") {
            appName = appName.replacingOccurrences(of: "-", with: "_")
        }
        return appName
    }


}

最后的结果输出如下:

2021-11-17 15:05:40.807418+0800 FindCassFromStringName[62983:3856323] Metal API Validation Enabled

this is a new class

this is a new class, parameter: Hello World!

return value: Hello World!

分段解析:

类型 1. 不需要传递参数,只执行类中的方法

        //类的名称
        let className = "NewClass"
        //根据"APP名称.类名称"查找对应的类
        let nsObjc = NSClassFromString(getAPPName() + "." + className) as! NSObject.Type
        //初始化类
        let objc = nsObjc.init()
        
        /* ******* 不需要传递参数,只执行类中的方法 ******* */
        
        // 将初始测试数据传递给测试类的testFunction方法
        let sel1 = NSSelectorFromString("testFunction")
        //判断类中的方法是否存在
        if (objc.responds(to: sel1)) {
            //执行类方法
            objc.perform(sel1)
        }

类型 2. 传递参数,执行类中的方法

        //类的名称
        let className = "NewClass"
        //根据"APP名称.类名称"查找对应的类
        let nsObjc = NSClassFromString(getAPPName() + "." + className) as! NSObject.Type
        //初始化类
        let objc = nsObjc.init()
        
        /* ******* 传递参数,执行类中的方法 ******* */
        let sel2 = NSSelectorFromString("testFunction2:")
        //判断类中的方法是否存在
        if (objc.responds(to: sel2)) {
            //执行类方法
            objc.perform(sel2, with: "Hello World!")
        }

类型 3. 执行类中的方法,获取返回值

        //类的名称
        let className = "NewClass"
        //根据"APP名称.类名称"查找对应的类
        let nsObjc = NSClassFromString(getAPPName() + "." + className) as! NSObject.Type
        //初始化类
        let objc = nsObjc.init()
        
        /* ******* 执行类中的方法, 获取返回值 ******* */
        let sel3 = NSSelectorFromString("testFunction3")
        //判断类中的方法是否存在
        if (objc.responds(to: sel3)) {
            //执行类方法
           let resp:String = objc.perform(sel3).takeUnretainedValue() as! String
            print("return value:", resp)
        }

注意事项:

  1. 调用类中方法前需要加上@objc
  2. 在查找类的时候需要加上APP名称,如果APP名称中有“-”,将其更改成“_”
  3. 在传递参数的时候,加以注意,在新类的参数前加上 “_ ”

完整Dome:

CJY5588/FindCassFromStringName: 【Swift】如何动态选择类以及类方法 (github.com)https://github.com/CJY5588/FindCassFromStringName

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三岁牧羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值