最近開發過程中遇到了獲取對象的所有屬性以及設置屬性值的問題,經過一番研究,最終實現了這個功能
直接上代碼
extension NSObject{
/**
獲取對象對於的屬性值,無對於的屬性則返回NIL
- parameter property: 要獲取值的屬性
- returns: 屬性的值
*/
func getValueOfProperty(property:String)->AnyObject?{
let allPropertys = self.getAllPropertys()
if(allPropertys.contains(property)){
return self.valueForKey(property)
}else{
return nil
}
}
/**
設置對象屬性的值
- parameter property: 屬性
- parameter value: 值
- returns: 是否設置成功
*/
func setValueOfProperty(property:String,value:AnyObject)->Bool{
let allPropertys = self.getAllPropertys()
if(allPropertys.contains(property)){
self.setValue(value, forKey: property)
return true
}else{
return false
}
}
/**
獲取對象的所有屬性名稱
- returns: 屬性名稱數組
*/
func getAllPropertys()->[String]{
var result = [String]()
let count = UnsafeMutablePointer<UInt32>.alloc(0)
let buff = class_copyPropertyList(object_getClass(self), count)
let countInt = Int(count[0])
for(var i=0;i<countInt;i++){
let temp = buff[i]
let tempPro = property_getName(temp)
let proper = String.init(UTF8String: tempPro)
result.append(proper!)
}
return result
}
}
