0

我有一个有 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 *class

4

3 回答 3

3

其他地方一定有问题,例如您正在通过的课程的名称。此演示程序按预期工作(为简洁起见压缩了布局):

#import <Foundation/Foundation.h>

@interface MyChild
+ (int) minHeight;
+ (int) minWidth;
@end

@implementation MyChild
+ (int) minHeight { return 100; }
+ (int) minWidth { return 300; }
@end

int main(int argc, const char *argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSString *className = [NSString stringWithString: @"MyChild"];
    Class theClass = NSClassFromString(className);
    NSLog(@"%d %d", [theClass minHeight], [theClass minWidth]);

    [pool drain];
    return 0;
}

输出:

2011-08-10 18:15:13.877 ClassMethods[5953:707] 100 300
于 2011-08-10T16:17:23.773 回答
2

这个答案似乎是相关的:How do I call +class methods in Objective C without reference the class?

您可以定义一个具有您要调用的方法的接口,然后具有以下内容:

Class<MyCoolView> class = NSClassFromString(childClassName);
CGRect frame = CGRectMake(0, 0, [class getMinWidth], [class getMinWidth]);
MotherClass *view = [[class alloc] initWithFrame:frame];

这应该消除编译器警告并使您的代码类型安全。

于 2011-08-10T15:50:01.837 回答
2
  • Objective-C 没有静态函数。它有方法;类或实例。

  • 不要在方法前面加上get; 这是为特定用例保留的,不是这样。

您的代码看起来或多或少是正确的。您确定其中childClassName包含正确的类名称吗?

一般来说,您的问题表明对 Objective-C 缺乏了解,或者至少假设 Obj-C 像 C++(或 Java)一样工作。我建议仔细阅读语言文档,因为它将回答各种元问题,这些问题将使所有这些都非常清楚。

于 2011-08-10T15:50:54.217 回答