美文网首页
Swift 5 动态获取一个类的属性,方法,和变量

Swift 5 动态获取一个类的属性,方法,和变量

作者: 龙之天下 | 来源:发表于2021-07-19 09:03 被阅读0次

    1、获取一个类的所有属性

    func getAllPropertys(view: Any?) -> [String] {
        var result = [String]()
        let count = UnsafeMutablePointer<UInt32>.allocate(capacity: 0)
        let buff = class_copyPropertyList(object_getClass(view), count)
        let countInt = Int(count[0])
        for i in 0..<countInt {
            if let temp = buff?[i] {
                let cname = property_getName(temp)
                let proper = String(cString: cname)
                result.append(proper)
            }
        }
        return result
    }
    

    2、获取一个类的成员变量

    func getAllIvarList(view: Any?) -> [String] {
        var result = [String]()
        let count = UnsafeMutablePointer<UInt32>.allocate(capacity: 0)
        let buff = class_copyIvarList(object_getClass(view), count)
        let countInt = Int(count[0])
        for i in 0..<countInt {
            if let temp = buff?[i],let cname = ivar_getName(temp) {
                let proper = String(cString: cname)
                result.append(proper)
            }
        }
        return result
    }

    相关文章

      网友评论

          本文标题:Swift 5 动态获取一个类的属性,方法,和变量

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