今天中午,偶然间发现nsobject的description的函数为类函数,我想覆盖这个函数,自定义类的描述,但要访问到成员变量,必须是成员函数(这个符合类函数的特性,类名直接调用),那么问题来了,我能直接覆盖这个函数么,需要其他关键字么?
研究了一个中午后,得出了结论:能覆盖,不需要任何关键字。
代码如下:
#import <Foundation/Foundation.h>
@interface TestCopyProtocol : NSObject<NSCopying>
+(NSInteger)testInherited;//好像没有纯虚方法,得用协议实现
@end
@interface TestCopyProtocolChild : TestCopyProtocol
-(NSInteger)testInherited;
@end
#import "TestCopyProtocol.h"
#import <UIKit/UIKit.h>
@implementation TestCopyProtocol
+(NSInteger)testInherited
{
return 3;
}
@end
@implementation TestCopyProtocolChild
-(NSInteger)testInherited
{
NSInteger r = [[super class] testInherited];
return r + 2;
}
@end
NSLog(@"%ld",[TestCopyProtocol testInherited]);//2
TestCopyProtocolChild* c = [[TestCopyProtocolChild alloc] init];
NSLog(@"%ld",[c testInherited]);//5
以前写代码从来没有这么写过,看到了class 开头的函数就绕过,没有想过要用成员函数覆盖它。
通过例子总结,oc的类函数只是调用方式和能否访问成员变量与成员函数有区别,其他都没有区别。
看来oc的动态特性还挺强大,有别的博客说oc的函数都是虚函数,如果不访问成员变量,尽量定义类函数。