Just like the topic says, there is a class, I want to set values for the properties in runtime,
and I have set the values which are inherited from NSObject use KVC mechanism and Reflect mechanism
, and I also need to set values for those who haven't inherited from NSObject, such as dataType is
Int, Double
. How can I make it?
Asked
Active
Viewed 940 times
0
-
If you want to reflect all properties and try to use KVC setValue:forKey: and value: function, it might be a bit of pain to write a generic method to do that (such as you want to encode or decode JSON to your class). For this topic, you can check the ServiceStack.Swift source code to see how this great library works: https://github.com/ServiceStack/ServiceStack.Swift – bubuxu Dec 29 '16 at 09:16
1 Answers
0
The signature of setValue(value: Any?, forKey: String)
takes Any?
instead of AnyObject?
. So it's not necessary for that value to be an NSObject subclass.
class MyClass : NSObject {
public var intField : Int = 100;
public var doubleField : Double = 10.0;
}
let a = MyClass()
a.setValue(200, forKey: "intField")
a.setValue(20.0, forKey: "doubleField")
print(a.intField) // Output: 200\n
print(a.doubleField) // Output: 20.0\n

ewcy
- 323
- 2
- 9
-
Thanks for ur anwser, but I forgot to say if the dataType is Optional? How to make it? – Shaw Dec 29 '16 at 09:19
-
You could take a look at this answer: http://stackoverflow.com/a/31353182/1755075 To quote from that answer, "If you really need this to be an Optional, and if you really need to use KVC on it, then declare it as NSNumber?, not Int?." – ewcy Dec 29 '16 at 09:24
-
I know to use NSNumber, but I don't want to, I just wonder is there has any other method to achieve the goal, thank u all the same. – Shaw Dec 30 '16 at 02:24