Objective-C dynamic properties at runtime?

后端 未结 3 2010
一整个雨季
一整个雨季 2020-12-02 17:56

Is it possible to create an Objective-C class that can have an arbitrary number of dynamic properties at runtime?

I want to be able to call mySpecialClass.anyP

3条回答
  •  情深已故
    2020-12-02 18:12

    You're asking different things. If you want to be able to use the bracket syntax mySpecialClass[@"anyProperty"] on instances of your class, it is very easy. Just implement the methods:

     - (id)objectForKeyedSubscript:(id)key
     {
          return ###something based on the key argument###
     }
    
     - (void)setObject:(id)object forKeyedSubscript:(id )key
     {
          ###set something with object based on key####
     }
    

    It will be called everytime you use the bracket syntax in your source code.

    Otherwise if you want to create properties at runtime, there are different ways to proceed, take a look at NSObject's forwardInvocation: method, or look at the Objective-C Runtime Reference for functions to dynamically alter a class...

提交回复
热议问题