Creating dynamic classes in Objective-C

I am a somewhat competent Rubin programmer. Yesterday, I finally decided to try my hand at using the Apple Cocoa frameworks. Help me figure out the ObjC method?

I am trying to get around objc_allocateClassPair and objc_registerClassPair . My goal is to dynamically generate multiple classes, and then be able to use them like any other class. Does it work in Obj C?

Selecting and registering class A , I get a compilation error when I call [[A alloc] init]; (he says 'A' Undeclared ). I can only instantiate A using the objc_getClass runtime objc_getClass . Is there a way to tell the compiler about A and pass it messages, how would I NSString ? Compiler flag or something else?

I have 10 or so other classes ( B , C , ...), all with the same superclass. I want to report them directly to code ( [A classMethod] , [B classMethod] , ...) without the need for objc_getClass . Am I trying to be too dynamic here or just mess up my implementation? It looks something like this ...

  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. 
+4
source share
4 answers

The reason [[A alloc] init]; explodes, is that the compiler does not know what A means. The compiler never knows that A even there.

Edit: Also, it looks like you want:

 @interface A : NSObject { NSString *myString; } - (id)initWithString:(NSString *)string; - (void)doItToIt; @end 

or maybe

 @interface NSString (MyPrivateExtension) - (void)doItToIt; @end 
+5
source

When you define a class in Objective-C, the compiler defines a new type. When you create a class dynamically, the compiler does not know this type, so your only choice is to use the class as id and dynamically send messages to it. Ruby is a dynamically typed language that probably uses the same mechanisms as the compiler when defining classes at runtime.

+1
source

Take a look at http://www.mikeash.com/pyblog/friday-qa-2010-11-6-creating-classes-at-runtime-in-objective-c.html and https://github.com/mikeash/MAObjCRuntime

It describes what you are trying to achieve and provides a great abstraction over raw Objective-C calls.

+1
source

Look at the fabulous F-Script and FSClass , which can do this with open source. FSClass defines a metaclass that can be subclassed at runtime.

It works using objc_allocateClassPair and objc_registerClassPair , but there are many other things that happen (outside of me!) That are likely to help.

0
source

Source: https://habr.com/ru/post/1304150/