0

I have an function which gives me back a Class:

- (Class)classForMyType:(NSString *)myType;

This class is given back like this:

return [MyFirstClass class];

In the code, where I call this function, I can store the Class like this:

Class myClass = [self classForMyType:@"foo"];

How can I instantiate a variable in the type of myClass? I want something like myClass *foo = [[myClass alloc] init], but this does not work.

gklka
  • 2,459
  • 1
  • 26
  • 53
  • 1
    if i understand your question right here it is: http://stackoverflow.com/questions/1174093/create-objective-c-class-instance-by-name – kocakmstf Feb 24 '15 at 20:07
  • You are right, I can instantiate the object by `id foo = [[myClass alloc] init];`, but this way the pointer won't have the proper class. Is it maybe possible to have a class pointer too? – gklka Feb 24 '15 at 20:09
  • with [[NSClassFromString(@"NameofClass") alloc] init]; you can instantiate with name. then if you want you can parse this class to your own class as i know – kocakmstf Feb 24 '15 at 20:13
  • The problem is the same, I can use this with `id` only, am I right? – gklka Feb 24 '15 at 20:21
  • `WhateverClassIHad* foo = (WhateverClassIHad*) [[myClass alloc] init];`. If you don't know `WhateverClassIHad` (or a suitable interface name) then you don't care anyway. – Hot Licks Feb 24 '15 at 20:30

1 Answers1

1

You can instantiate it like this if you're using a string.

id object = [[NSClassFromString(@"NameofClass") alloc] init];

Based on your code it looks like you're not type-casting your class. Either instantiate it like this with an id

id foo = [[myClass alloc] init]

Or explicitly type-cast like this (notice MyClass is not your instance variable but your actual class name):

MyClass *foo = [[myClass alloc] init]
Chase
  • 2,206
  • 1
  • 13
  • 17
  • If I would know the exact class name at that point, I would not have created a function for giving it back :) – gklka Feb 24 '15 at 20:20
  • lol yeah thats what I figured, but I put it in just in case. I don't think its possible to do what you want. I think the best you can do is instantiate it as its parent class if you know that for sure, but other than that I don't think you can do it without an id but I'll keep looking! – Chase Feb 24 '15 at 20:25
  • The cast on the right side of the assignment does nothing. You never need to cast an expression of type `id` to another object type. – jlehr Feb 24 '15 at 23:00
  • It would be `id` not `id *` – newacct Feb 24 '15 at 23:15
  • My b guys - I corrected both mistakes. the id * was a typo and you're right about the right type-cast not doing anything. I've updated my answer. – Chase Feb 24 '15 at 23:16