NSClassFromString(MyClassName) 比调用 MyClass 的类函数
我有一个带有 7 个孩子的 UIViewCustom 类。 每个孩子都有自己的类函数,用于帮助
+(int) minHeight;
+(int) minWidth;
在 UITableView 中启动我选择其中一个类,然后调用函数“-insertNewObjectWithClassName:(NSString*)childClassName”。
在该函数中,我想根据类名创建实例,所以我尝试了
Class *class = NSClassFromString(childClassName);
CGRect frame = CGRectMake(0, 0, [class minWidth], [class minWidth])
MotherClass *view = [[class alloc] initWithFrame:frame];
但不幸的是无法调用静态函数。
有没有办法让编译器说这个类不仅是一个类,而且还是一个 MotherClass 来告诉他这个函数?
非常感谢!
编辑: 警告:语义问题:未找到方法“-minWidth”(返回类型默认为“id”)
解决方案:类 class 而不是类 *class
i got a UIViewCustom Class with 7 childs.
each of the childs got their own class functions for helping initiating
+(int) minHeight;
+(int) minWidth;
in a UITableView i select one of the classes and the function "-insertNewObjectWithClassName:(NSString*)childClassName" gets called.
In that function i want to create the instance depending to the classname, so i tryed
Class *class = NSClassFromString(childClassName);
CGRect frame = CGRectMake(0, 0, [class minWidth], [class minWidth])
MotherClass *view = [[class alloc] initWithFrame:frame];
But unfortunately the static function can't be called.
Is there a way, to say the compiler that class is not just a Class but also a MotherClass to tell him the function?
thank you very much!
EDIT:
Warning: Semantic Issue: Method '-minWidth' not found (return type defaults to 'id')
SOLUTION: Class class instead of Class *class
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
其他地方一定有问题,例如您正在传递的班级名称。该演示程序按预期工作(为简洁起见,布局紧凑):
输出:
Something must be wrong elsewhere, e.g. the name of the class you are passing. This demo program works as expected (layout compacted for brevity):
Output:
Objective-C 没有静态函数。它有方法;类或实例。
不要在方法前添加
get
;这是为特定用例保留的,但不是这样。您的代码看起来或多或少是正确的。您确定
childClassName
包含正确的类名称吗?一般来说,你的问题表明对 Objective-C 有点缺乏理解,或者至少假设 Obj-C 的工作方式与 C++(或 Java)类似。我建议仔细阅读语言文档 因为它将回答各种元问题,使所有这些变得非常清晰。
Objective-C does not have static functions. It has Methods; class or instance.
do not prefix methods with
get
; that is reserved for a particular use case, this isn't it.Your code looks more or less correct. Are you sure that
childClassName
contains the correct name of the class?In general, your question indicates a bit of a lack of an understanding of Objective-C or, at the least, an assumption that Obj-C works like C++ (or Java). I would suggest perusing the language documentation as it will answer various meta questions that will make all of this pretty clear.
这个答案似乎相关:如何我可以在 Objective C 中调用 +class 方法而不引用该类吗?
您可以定义一个接口,其中包含您想要调用的方法,然后具有类似以下内容:
这应该消除编译器警告并使您的代码类型安全。
This answer seems related: How do I call +class methods in Objective C without referencing the class?
You can define an interface that has the methods you want to call and then have something like:
This should eliminate compiler warnings and make your code typesafe.