swift – 有没有办法获得变量列表和类的功能

前端之家收集整理的这篇文章主要介绍了swift – 有没有办法获得变量列表和类的功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法获得变量列表和类的功能

例如:
如果我的课程如下

class Person {
    var age: Int!
    var name: String! 
    func isOlder(from person: Person) -> Bool { }
    func hasSameName(as person: Person) -> Bool { }
}

我想获得2个名单:

1. [age,name]
2. [isOlder( _ : ),hasSameName( _ : )]

或类似的东西.

谢谢

解决方法

在目标C中

#import <objc/runtime.h>

getDetailsOfClass(Class clz) {

    unsigned int methodCount = 0;
    Method *methods = class_copyMethodList(clz,&methodCount);

    printf("Found %d methods on '%s'\n",methodCount,class_getName(clz));

    for (unsigned int i = 0; i < methodCount; i++) {
        Method method = methods[i];

        printf("\t'%s' has method named '%s' of encoding '%s'\n",class_getName(clz),sel_getName(method_getName(method)),method_getTypeEncoding(method));
    }

    free(methods);
}

调用:getDetailsOfClass(class)

在斯威夫特

遵循SO Post.已实施相同并取得成功.

获取方法名称

func printMethodNamesForClass(cls: AnyClass) {
    var methodCount: UInt32 = 0
    let methodList = class_copyMethodList(cls,&methodCount)
    if methodList != nil && methodCount > 0 {
        enumerateCArray(methodList,methodCount) { i,m in
            let name = methodName(m) ?? "unknown"
            println("#\(i): \(name)")
        }

        free(methodList)
    }
}
func enumerateCArray<T>(array: UnsafePointer<T>,count: UInt32,f: (UInt32,T) -> ()) {
    var ptr = array
    for i in 0..<count {
        f(i,ptr.memory)
        ptr = ptr.successor()
    }
}
func methodName(m: Method) -> String? {
    let sel = method_getName(m)
    let nameCString = sel_getName(sel)
    return String.fromCString(nameCString)
}
func printMethodNamesForClassNamed(classname: String) {
// NSClassFromString() is declared to return AnyClass!,but should be AnyClass?
let maybeClass: AnyClass? = NSClassFromString(classname)
if let cls: AnyClass = maybeClass {
printMethodNamesForClass(cls)
}
else {
println("\(classname): no such class")
}
}

快乐编码..

猜你在找的Xcode相关文章