spring
spring

Reputation: 18487

Use a Class name stored in a variable to call a Class method?

I'm probably over-thinking this/wasting time trying to avoid a bit of conditional code - so I thought I would ask. I've seen some other questions @ this sort of thing but they were using php or some other language.

At the most basic, can I do something like this (I know the syntax is wrong):

        Class * var = @"Playback_Up";
        // call Class method to get default settings
        NSMutableDictionary * dict = [var getPlaybackDefaults]; 

Why do I want to do this? To avoid a bunch of conditionals. I have an app where a using can select from a range of playback "types" - each type is handled by a subclass of a "Playback" class. It would be convenient to store the class names in an array and then when a selection is made (from a tableView) call the selected class, create an instance of it, etc.

Is this possible or am I digging myself into a hole here?

Upvotes: 2

Views: 1120

Answers (1)

Rob Napier
Rob Napier

Reputation: 299345

The correct syntax for your first line is:

Class var = NSClassFromString(@"Playback_Up");

The rest is fine, and I use this kind of technique more frequently than you might imagine.

(Except that "Playback_Up" should never be the name of a class of course.)


EDIT: Do note Paul.s's comment below. Using +class is preferred if you can hard-code the class at compile time.

Upvotes: 5

Related Questions