#如果你想在运行时通过给定的字符串来动态创建对应的对象并且调用某中的方法。
#如果你得到一个id对象,但不知道该对象是否含有某方法,如果有就调用它。
请看下面的例子:
DynObj.h
#import <Foundation/Foundation.h>
@interface DynObj : NSObject {
NSString *name;
}
@property(nonatomic,retain) NSString* name;
- (id) init;
- (void) dealloc;
-(void) show;
@end
DynObj.m
#import "DynObj.h"
@implementation DynObj
@synthesize name;
- (id)init
{
if((self = [super init]))
{
name= @"123";
}
return self;
}
- (void) dealloc
{
[name release];
[super dealloc];
}
-(void) show
{
NSLog(@"%@", name);
}
@end
main.m
#import <Foundation/Foundation.h>
#import "DynObj.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//动态创建对象
Class classToInstantiate = NSClassFromString(@"DynObj");
id newObject = [[classToInstantiate alloc] init];
[newObject show];
//通过选择器判断是否存在某方法
if([newObject respondsToSelector:@selector(show)])
{
[newObject show];
}
[pool drain];
return 0;
}
输出:
2011-04-29 09:35:52.615 demo02[1980:903] 123
2011-04-29 09:35:52.618 demo02[1980:903] 123
Program ended with exit code: 0