swift 獲取類的所有屬性、獲取對象的屬性值、設置對象的屬性值


 

最近開發過程中遇到了獲取對象的所有屬性以及設置屬性值的問題,經過一番研究,最終實現了這個功能

 

直接上代碼

 

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

    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM