Reputation: 3390
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
Upvotes: 0
Views: 3927
Reputation: 27354
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.
Upvotes: 1
Reputation: 28806
Something must be wrong elsewhere, e.g. the name of the class you are passing. This demo program works as expected (layout compacted for brevity):
#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;
}
Output:
2011-08-10 18:15:13.877 ClassMethods[5953:707] 100 300
Upvotes: 3
Reputation: 162712
Objective-C does not have static functions. It has Methods; class or instance.
do not prefix methods with get
; that is reserved for a particular use case, this isn't it.
Your code looks more or less correct. Are you sure that childClassName
contains the correct name of the class?
In general, your question indicates a bit of a lack of an understanding of Objective-C or, at the least, an assumption that Obj-C works like C++ (or Java). I would suggest perusing the language documentation as it will answer various meta questions that will make all of this pretty clear.
Upvotes: 2