objective-c - NSClassFromString(MyClassName) 比调用 MyClass 的类函数

标签 objective-c ios class static-functions

我有一个有 7 个 child 的 UIViewCustom 类。 每个 child 都有自己的类(class)功能来帮助发起

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

但不幸的是静态函数无法调用。

有没有办法,让编译器说 class 不仅仅是一个 Class 还是一个 MotherClass 来告诉他这个函数?

非常感谢!

编辑: 警告:语义问题:未找到方法“-minWidth”(返回类型默认为“id”)

解决方案:类 class 而不是 Class *class

最佳答案

一定是其他地方出了问题,例如你正在传递的类的名称。该演示程序按预期工作(为简洁起见,布局紧凑):

#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

关于objective-c - NSClassFromString(MyClassName) 比调用 MyClass 的类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7013669/

相关文章:

iphone - 循环引用,目标 - c

iphone - 将文件类型与我的 Iphone 应用相关联

java - 声明变量、方法和类?

c++ - 比较 C 和 C++ 中的结构

objective-c - iCloud 同步钥匙串(keychain)

iphone - 符合iOS4

ios - 有没有更好的方法来深度复制 UIWebView?

ios - 在 iOS 8 中更改 UIBarButtonItems 之间的间距

ios - 复杂的正则表达式文本修改

C++ 使用来自类似虚拟公共(public)类的成员函数