user89793
user89793

Reputation: 21

Static initializer in Objective-C upon Class Loading

I am trying to build something to dynamically instantiate an object from class-name similar to how Java's Class.forName method works, e.g.

Class klass = Class.forName("MyClass");
Object obj = klass.instantiate(...

I didn't see any such behavior in Objective-C so I would like to call a method to register Class when an Objective-C class is loaded. Basically, I would like to call a method that registers my class, e.g.

+ (void)mystatic {
  [NSKeyedUnarchiver setClass:[self class] forClassName:"MyClass"]
}

Is there a way to do this in Objective-C on OS X platform?

Thanks.

Upvotes: 2

Views: 3270

Answers (3)

zaccox
zaccox

Reputation: 73

You can also say

Class myClass = [[NSBundle mainBundle] classNamed: @"MyClassName];
id myInstance = [[myClass alloc] init];

This frequently helps with cases when the runtime may not have come across your class yet.

Upvotes: 0

Quinn Taylor
Quinn Taylor

Reputation: 44769

First, there is indeed such an equivalent in Objective-C — as @Louis suggested, use NSClassFromString().

Second, if you want a static constructor like in Java, you can do that as well with the +initialize method. See this related SO question.

Upvotes: 3

Louis Gerbarg
Louis Gerbarg

Reputation: 43452

You want to use NSClassFromString, like this:

Class klass = NSClassFromString(@"MyClass");
id obj = [[klass alloc] init];

Upvotes: 4

Related Questions