[英]Inability to create my UIImageView classes from string
I am creating subclasses of UIImageView
class, something like LittleImageView
, RedImageView
, etc. 我正在创建UIImageView
类的子类,如LittleImageView
, RedImageView
等。
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. 显然,例如,objective-c尝试执行[UIImageView novo]
而不是[RedImageView novo]
。
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)... 我无法完全重现您的经验,但是您应该考虑一些更改:(1)将构造函数声明为返回派生类型,(2)将局部变量声明为派生类型,(3)使用派生类分配(自己,而不是超级)...
// 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. 现在,您可以在其他地方使用,而不必在本地变量声明中粗略地使用id
。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.