SpaceDog SpaceDog - 2 months ago 23
iOS Question

Inability to create my UIImageView classes from string

I am creating subclasses of

class, something like
, etc.

These subclasses have this convenience method for the creation of specific images:

+ (UIImageView *)novo {
UIImageView *newImage = [[super alloc] initWithImage:...
// do stuff
return newImage;

When I try to create such classes using this new command by string

id newObject = [NSClassFromString(nameOfClass) novo];

I get a crash with "unrecognized selector sent to class". Apparently objective-c is trying to do a
[UIImageView novo]
instead of doing a
[RedImageView novo]
, for instance.

Any ideas how to solve this?


I can't reproduce your experience exactly, but there are a few changes you should consider: (1) declare the constructor as returning the derived type, (2) declare the local variable as the derived type, (3) used the derived class to alloc (self, not super)...

// in MyImageView.h
+ (instancetype)myImageView:(UIImage *)image;

// in MyImageView.m
+ (instancetype)myImageView:(UIImage *)image {
    MyImageView *miv = [[self alloc] initWithImage:image];
    // ...
    return miv;

Now you can use elsewhere without the sketchy use of id in your local variable declaration. It looks like this, and in my test, generates instances of the correct type...

MyImageView *firstTry = [MyImageView myImageView:nil];
MyImageView *secondTry = [NSClassFromString(@"MyImageView") myImageView:nil];

NSLog(@"%@, %@", firstTry, secondTry);