13

You can create a class reference with the following code:

Class M = [NSMutableString class]; // NSMutableString (for example).

You can then call methods on that saved class with code like this:

[M string];

But can you create instances, from that class name (I know the following doesn't work)?

M *newInstance;
Alex Coplan
  • 13,211
  • 19
  • 77
  • 138

1 Answers1

19

You can allocate a new instance of the class like this

id instance = [[M alloc] init];

+alloc is a class method just like string is in your example so the rules are the same.

Joe
  • 56,979
  • 9
  • 128
  • 135
  • This creates a generic, `id` object.. How can you instantiate a "fully qualified", dot-addressable instance of the class. That is the question.. – Alex Gray Jul 08 '13 at 03:39
  • First, that was not the question, the question was can you create instances of the class which this answers. Once you start using reflection you can not do what you are asking unless you cast it to its fully qualified type. – Joe Jul 08 '13 at 11:52
  • and how to call methods of this instance? – user25 Apr 10 '18 at 13:54