Inability to create my UIImageView classes from string

99封情书 提交于 2019-12-25 13:47:44

问题


I am creating subclasses of UIImageView class, something like LittleImageView, RedImageView, 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?


回答1:


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);


来源:https://stackoverflow.com/questions/40819035/inability-to-create-my-uiimageview-classes-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!