經過類名和方法名,實現對函數得調用

1.BaseClass是基類,SubClass繼承BaseClass,而且重寫基類的manageMethod方法,經過類名@"SubClass"獲取類,並經過基類調用manageMethod方法,實現工廠模式。html

 NSString *className      = @"SubClass";java

    NSString *param          = [dic objectForKey:@"param"];ui

    Class ob = NSClassFromString( className );spa

    BaseClass *baseObject = [[ob alloc] init];orm

    [baseObject manageMethod:methodName  param:param];htm

 

2.在subClass中實現manageMethod方法,並經過方法名調用方法,找了好久才發現有NSSelectorFromString這個方法,就不用像java那些去實現map或者去反射,大概機制應該是相同的吧。blog

-(void)manageMethod:(NSString *)methodName param:(NSString *)param繼承

{get

     [self performSelector:NSSelectorFromString( methodName ) withObject:param afterDelay:0];it

 

還有一種經過方法名調用方法的方式:http://www.cnblogs.com/tiechui/p/3819805.html

 id theClass = objc_getClass([@"SubClass" UTF8String]);

unsigned int outCount;

 Method *m =  class_copyMethodList(ob, &outCount);

for (int i = 0; i<outCount; i++) {

        SEL a = method_getName(*(m+i));

        NSString *sn = NSStringFromSelector(a);

        if ( [sn isEqualToString:methodName] ) {

             [baseObject performSelector:a withObject:param afterDelay:0 ];

        }

    }

相關文章
相關標籤/搜索