Is it possible to add properties to an Objective C object at runtime?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s possible to add formal properties to a class via
class_addProperty():The first two parameters are self-explanatory. The third parameter is an array of property attributes, and each property attribute is a name-value pair which follow Objective-C type encodings for declared properties. Note that the documentation still mentions the comma-separated string for the encoding of property attributes. Each segment in the comma-separated string is represented by one
objc_property_attribute_tinstance. Furthermore,objc_property_attribute_taccepts class names besides the generic@type encoding ofid.Here’s a first draft of a program that dynamically adds a property called
nameto a class that already has an instance variable called_privateName:Its (trimmed) output:
The getter and setter methods should be written more carefully but this should be enough as an example of how to dynamically add a formal property at runtime.