Search code examples
objective-ciosclassstatic-functions

NSClassFromString(MyClassName) than calling class function of MyClass


i got a UIViewCustom Class with 7 childs. each of the childs got their own class functions for helping initiating

+(int) minHeight;
+(int) minWidth;

in a UITableView i select one of the classes and the function "-insertNewObjectWithClassName:(NSString*)childClassName" gets called.

In that function i want to create the instance depending to the classname, so i tryed

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

But unfortunately the static function can't be called.

Is there a way, to say the compiler that class is not just a Class but also a MotherClass to tell him the function?

thank you very much!

EDIT: Warning: Semantic Issue: Method '-minWidth' not found (return type defaults to 'id')

SOLUTION: Class class instead of Class *class


Solution

  • This answer seems related: How do I call +class methods in Objective C without referencing the class?

    You can define an interface that has the methods you want to call and then have something like:

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

    This should eliminate compiler warnings and make your code typesafe.