-->

Dynamic generation of data members

2020-07-27 03:44发布

问题:

I have made one application which can parse the given xml file independent of its tags . It is working well and good for at list single level of xml file .I want to assign the xml values on the object.As xml can be different the class also must be generic one and the data members also . I can achieve the generic data members by using the data type id. But problem is different xml can have different number of data types. so is it possible to decide the number of data members at the run time ? (here i am loading the xml two time is it any way useful to achieve our goal?)

回答1:

Key-Value Coding perfectly matches your need, you can rather use NSMutableDictionary if you want something quick & simple.



回答2:

Coming here from another question of the OP's. Just to elaborate on A-Live's answer:

If the object is just a completely generic holder of values, then you should just use an NSMutableDictionary. There's no particular need to use KVC for that, although it works.

If the object has some fixed properties plus an arbitrary number of ad hoc properties or if it has to have some behaviors in addition to holding values, then you can wrap an NSMutableDictionary in a custom class. In this case, your custom class would implement -valueForUndefinedKey: to retrieve values from the dictionary when the key doesn't correspond to any of the class's normal properties. Likewise, it would implement -setValue:forUndefinedKey: to allow for setting ad hoc properties by storing them in the dictionary.

Once both of those methods are defined, then a client of the class could use KVC to get and set property values, using -valueForKey: and -setValue:forKey:.

Either of the "undefined-key" methods you implement could be completely permissive by passing any and all keys through to the dictionary, or they could check the key against a list of allowed/known properties. This list would still be established at run time rather than fixed at compile time, but, if you have that information from somewhere, it establishes a bit of extra safety. For unknown/disallowed keys, just call through to super's implementation.

Both methods – more likely the setter – can also implement behaviors relating to the ad hoc properties, if you want.



回答3:

You can use Touch XML , TBXML to solve your problem.