object C—类中函数的调用

时间:2023-08-26 23:12:41

Object C—类中函数的调用

创建,三个类。然后,在代码中调用相同名字的函数。观察他们的调用次序。

@interface test : NSObject
- (void)print;
@end @implementation test
- (void)print{
NSLog(@"test0");
}
@end @interface test1 : test
- (void)print;
@end @implementation test1
- (void)print{
NSLog(@"test1");
}
@end @interface test2 : test
- (void)print;
@end @implementation test2
- (void)print{
NSLog(@"test2");
}
@end

我们创建了三个类,然后在下面使用。

    test1 *test11 = [[test1 alloc] init];
[test11 print];
test2 *test22 = [[test2 alloc] init];
[test22 print]; test *test00;
test00 = test11;
[test00 print];

输出结果:

2015-05-22 14:00:41.858 test[1034:75692] test0

2015-05-22 14:00:41.858 test[1034:75692] test2

2015-05-22 14:00:41.858 test[1034:75692] test0

总结:在函数预编译的时候,test00认为调用print函数为test类申明中的函数,但是在真正编译的时候,发现这个test00指针指向了一个test11(test1类的实例),因此,按照函数方法从子类向父类搜索的性质来看,这个方法调用的是test1中的实现方法。