最近开发过程中遇到了获取对象的所有属性以及设置属性值的问题,经过一番研究,最终实现了这个功能
@H_301_3@
直接上代码
extension NSObject{
/**
- returns: 属性的值
*/
@H_404_44@func getValueOfProperty(property:String)->AnyObject?{
@H_404_44@let allPropertys = @H_404_44@ self.getAllPropertys()
@H_404_44@if(allPropertys.contains(property)){
@H_404_44@return @H_404_44@ self.valueForKey(property)
@H_301_3@
}@H_404_44@else{
@H_404_44@return @H_404_44@ nil
}
}
/**
设置对象属性的值
- parameter property: 属性
- parameter value: 值
- returns: 是否设置成功
*/
@H_404_44@func setValueOfProperty(property:String,value:AnyObject)->Bool{
@H_404_44@let allPropertys = @H_404_44@ self.getAllPropertys()
@H_404_44@if(allPropertys.contains(property)){
@H_404_44@self.setValue(value,forKey: property)
@H_404_44@return @H_404_44@ true
}@H_404_44@else{
@H_404_44@return @H_404_44@ false
}
}
/**
*/
@H_404_44@func getAllPropertys()->[String]{
@H_404_44@var result = [String]()
@H_404_44@let count = UnsafeMutablePointer<UInt32>.alloc(0)
@H_404_44@let buff = class_copyPropertyList(object_getClass(@H_404_44@self),count)
@H_404_44@let countInt = Int(count[0])
@H_404_44@for(@H_404_44@var i=0;i<countInt;i++){
@H_404_44@let temp = buff[i]
@H_404_44@let tempPro = property_getName(temp)
@H_404_44@let proper = String.@H_404_44@init(UTF8String: tempPro)
result.append(proper!)
}
@H_404_44@return result
}
}
@H_301_3@
@H_301_3@
@H_544_301@如有问题欢迎随时联系我 ———— LC