Objective-C语法之动态类型(isKindOfClass, isMemberOfClass,id)等(二)

2014-11-23 23:55:07 · 作者: · 浏览: 40
ame:)] == YES ) {
NSLog(@"Teacher instance responds to setName: method" );
}
打印结果:
[cpp]
2012-07-04 14:52:29.378 ObjectiveCTest[2961:f803] Teacher instance responds to teach method
2012-07-04 14:52:29.379 ObjectiveCTest[2961:f803] Teacher instance responds to setName: method

3、Objective-C的id类型

C++ 使用的是强类型:对象必须符合其类型,否则不能通过编译。在 Objective-C 中,id类型类似于(void*) ,可以指向任何类的实例。而不需要强制转换。
下面看看使用,
先把Teacher类中的 teach方法修改一下,改成
-(void)teach
{
NSLog(@"%@ 教数学" ,name);
}
然后实现并调用
[cpp]
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

Person *person = [[Person alloc] init];
Teacher *teacher = [[Teacher alloc] init];

id p = person;
id t = teacher;
[t setName:@"张三老师"];
[t teach];

[person release];
[teacher release];
[pool release];
打印结果:
[cpp] view plaincopy
2012-07-04 14:57:55.905 ObjectiveCTest[3085:f803] 张三老师 教数学


作者:totogo2010