0

Let's say I have:

ThisClass *castHere = [[ThisClass alloc] init];

But I effectively want:

ThisClassChosenAtRuntime *castHere = [[ThisClassChosenAtRuntime alloc] init];

I'm sure there is some smarter way to go about this. But this is the result I'm after. I already have castHere subjected to setValue forKey statements. But I want to dynamically setup *castHere.

admdrew
  • 3,790
  • 4
  • 27
  • 39
Bill3
  • 61
  • 9
  • 3
    your question is not clear. Do you want to change the name of ur class? – Frans Raharja Kurniawan Sep 22 '14 at 17:02
  • A partial answer is to use `id castHere = ...` but the rest of it depends on how you're choosing which class you want to `alloc`. – Phillip Mills Sep 22 '14 at 17:04
  • I have several classes and want to choose which one is applied to *castHere. There are different property names with each class. – Bill3 Sep 22 '14 at 17:05
  • Repeating, how do you choose? If it's just a simple `if` or `switch` or something, then the `id` trick is all you need. If you're trying to decide on a class by using its name (as a string) things get more complicated. – Phillip Mills Sep 22 '14 at 17:08
  • 1
    I'd like to pass the name over as a string. I could use `if` statements or `switch` and get through this. But I'm looking to future proof without revisiting this method. Sorry for making admdrew work overtime. :) – Bill3 Sep 22 '14 at 17:15
  • possible duplicate of [Objective-C class -> string like: \[NSArray className\] -> @"NSArray"](http://stackoverflow.com/questions/2331983/objective-c-class-string-like-nsarray-classname-nsarray) – Craig Otis Sep 22 '14 at 17:23
  • You can't "cast" with a variable type. Period. But there's absolutely no need to. – Hot Licks Sep 22 '14 at 17:32
  • The type is not varied. The property names are changing. – Bill3 Sep 22 '14 at 18:01

1 Answers1

3

If you can build up the class name as a string, then it's easy.

NSString *className = @"ThisClassChosenAtRuntime";
id object = [[NSClassFromString(className) alloc] init];

Note that the return type is id. You can call any method from an instance of type id.

For something more type safe and if you can rely on a base class than you can.

NSString *className = @"ThisClassChosenAtRuntime";
MyBaseClass *object = [[NSClassFromString(className) alloc] init];
Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117