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的函数都是虚函数,如果不访问成员变量,尽量定义类函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值