class func propertyList() -> [String] {
var count: UInt32 = 0
//获取类的属性列表,返回属性列表的数组,可选项
let list = class_copyPropertyList(self, &count)
print("属性个数:\(count)")
//遍历数组
for i in 0..<Int(count) {
//根据下标获取属性
let pty = list?[i]
//获取属性的名称<C语言字符串>
//转换过程:Int8 -> Byte -> Char -> C语言字符串
let cName = property_getName(pty!)
//转换成String的字符串
let name = String(utf8String: cName)
print(name!)
}
free(list) //释放list
return []
}
class func guard_propertyList() -> [String] {
var count: UInt32 = 0
//1.获取类的属性列表,返回属性列表的数组,可选项
let list = class_copyPropertyList(self, &count)
print("属性个数:\(count)")
for i in 0..<Int(count) {
//使用guard语法,一次判断每一项是否有值,只要有一项为nil,就不再执行后续的代码
guard let pty = list?[i],
let cName = property_getName(pty),
let name = String(utf8String: cName)
else {
//继续遍历下一个
continue
}
print(name)
}
free(list)
return []
}
网友评论