djibouti33
djibouti33

Reputation: 12132

Subclass for Superclass with @dynamic @properties

I'm using PAPreferences to manage app specific preferences/defaults. It's basically a layer on top of NSUserDefaults that lets me read/write data to NSUserDefaults as if I was just using a normal class.

The basic setup is to subclass PAPreferences, add @properties in your subclass' .h file, and declare them as @dynamic in the .m file.

The class hierarchy looks like this:

- PAPreferences
    - MyPreferences // all @properties defined here, and set in -init

My project builds many different targets, and each time I add a new target, I have to duplicate the previous MyPreferences file. A lot of code is duplicated, and each time I want to make a change to my app's preferences, I have to do so in many different files.

I'd like to create a class hierarchy like so:

- PAPreferences
    - MyPreferencesBase // all @properties defined here
        - MyPreferences // all @properties set in -init

With the previous class hierarchy, my app is crashing when MyPreferenes#init is run and I set the first instance variable (unrecognized selector sent to instance).

How can I write a subclass for a superclass whose @properties are set to be @dyanmic?

Upvotes: 0

Views: 373

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90571

The problem is not general to a superclass which implements properties dynamically. It's specific to the implementation of PAPreferences.

In -[PAPreferences init], it examines the current class's properties by using the runtime function class_copyPropertyList(). That function is documented to only return the properties declared in that class, not its superclass(es). As a consequence, PAPreferences is blind to the dynamic properties of the superclass.

[PAPreferences init] would need to walk up the chain of superclasses, processing the properties of all of the classes. It would stop when it reached itself. It might also need to adjust which class it adds a method to in +resolveInstanceMethod:.

Upvotes: 1

Related Questions