无法从字符串创建我的UIImageView类 [英] Inability to create my UIImageView classes from string

查看:75
本文介绍了无法从字符串创建我的UIImageView类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建 UIImageView 类的子类,例如 LittleImageView RedImageView ,等等。

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

我收到了无法识别的选择器发送给班级崩溃的消息。显然,例如,objective-c尝试执行 [UIImageView novo] 而不是执行 [RedImageView 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)将构造函数声明为返回派生类型,(2)将局部变量声明为派生类型,(3)使用派生类进行分配(自身,不是超级)...

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

现在您可以在其他地方使用,而无需粗略地使用 id 在您的本地变量声明中。看起来像这样,并在我的测试中,生成了正确类型的实例...

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

这篇关于无法从字符串创建我的UIImageView类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆