Can you add a property at runtime when encoding with Objective-C

I was wondering if it is possible at runtime to dynamically add new properties to an Objective-C object instance?

My initial thought was simply to override getValueForKey to "fake" the property, but it doesn't seem to work with CoreAnimation. What I want to achieve is the ability to animate custom properties. I was able to get this to work if I create a subclass of CALayer and add the declared properties to my subclass. If I try to use getValueForKey / setValueForKey, it seems that CoreAnimation does not care about this and is explicitly looking for declared properties.

I would like to be able to dynamically add properties, because I may not know which property I want to animate before execution. I can, of course, create a subclass of CALayer that has all the properties that I would ever want to revive ... but just wondering if there is a better way to do this ...

Thanks,

Peter

+4
source share
2 answers

Have you tried overriding valueForUndefinedKey: instead? (I do this in a custom subclass of NSObject, which can have various properties whose names are pulled from the database.)

+3
source

You can override -respondsToSelector: and -doesNotUnderstand: to dynamically process incoming messages, if necessary.

+1
source

All Articles