使用其他JSON-API时,可以方便地在应用程序和调用服务器时保持属性的一致性 对于这个例子:
class Picture: NSManagedObject {
@NSManaged var copyright: String
@NSManaged var likes: NSNumber
}
func postToServer() {
let newPicture = Picture(copyright: "haaakon", likes:433)
let arguments = @{
newPicture.copyright.selectorName : newPicture.copyright,
newPicture.likes.selectorName : newPicture.likes
}
println(arguments)
}
println应该给出这个输出:
{ "copyright": "haaakon", "likes": "433" }
如何在给定属性上创建扩展(或其他解决方案)时如何进行基本相同:
NSStringFromSelector(Selector(newPicture.copyright)) // returns "copyright"
newPicture.copyright.selectorName // returns "copyright"
答案 0 :(得分:0)
试试这个:
extension Picture{
func dictionary() -> Dictionary<String, AnyObject> {
var outCount: CUnsignedInt = 0
let properties: UnsafeMutablePointer<objc_property_t> = class_copyPropertyList(self.dynamicType, &outCount)
var result: Dictionary<String, AnyObject> = Dictionary()
for var i = 0; i < Int(outCount); i++ {
var property : NSString! = NSString(CString: property_getName(properties[i]), encoding: NSUTF8StringEncoding)
result[property] = self.valueForKey(property)
}
return result
}
}