1. 程式人生 > >OC類方法和成員方法

OC類方法和成員方法

今天中午,偶然間發現nsobjectdescription的函式為類函式,我想覆蓋這個函式,自定義類的描述,但要訪問到成員變數,必須是成員函式(這個符合類函式的特性,類名直接呼叫),那麼問題來了,我能直接覆蓋這個函式麼,需要其他關鍵字麼?

研究了一箇中午後,得出了結論:能覆蓋,不需要任何關鍵字。

程式碼如下:

#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的函式都是虛擬函式,如果不訪問成員變數,儘量定義類函式。