在Objective C中构建动态类

kje*_*ll_ 4 ruby dynamic objective-c objective-c-runtime

我是一位有能力的红宝石程序员.昨天我决定最终尝试使用Apple的Cocoa框架.帮我看看ObjC的方式吗?

我想围绕让我的头objc_allocateClassPairobjc_registerClassPair.我的目标是动态生成一些类,然后能够像任何其他类一样使用它们.这是否适用于Obj C?

分配和注册类后A,我在调用时遇到编译错误[[A alloc] init];(它说'A' Undeclared).我只能A使用运行时的objc_getClass方法实例化.有没有办法告诉编译器,A并像我一样传递消息NSString?编译器标志还是什么?

我有10个左右,其他类(B,C,...),都具有相同的超类.我想直接在代码中(消息他们[A classMethod],[B classMethod]......),而无需objc_getClass.我想在这里过于动态还是只是拙劣地实施我的实施?它看起来像这样......

 NSString *name = @"test";  
 Class newClass = objc_allocateClassPair([NSString class], [name UTF8String], 0);  
 objc_registerClassPair(newClass);  

 id a = [[objc_getClass("A") alloc] init];  
 NSLog(@"new class: %@ superclass: %@", a, [a superclass]);  
 //[[A alloc] init]; blows up.
Run Code Online (Sandbox Code Playgroud)

Wil*_*and 5

[[A alloc] init];爆炸的原因是编译器不知道是什么A意思.编译器永远不会知道它就在A那里.

编辑:此外,它看起来像你想要的是:

@interface A : NSObject {
  NSString *myString;
}

- (id)initWithString:(NSString *)string;

- (void)doItToIt;

@end
Run Code Online (Sandbox Code Playgroud)

也许

@interface NSString (MyPrivateExtension)

- (void)doItToIt;

@end
Run Code Online (Sandbox Code Playgroud)