Objective-C 之Extension

Objective-C 之Extension

class extension:类扩展

类扩展与 category 有相似性,但在编译时它只能被添加到已有源代码的一类中(该类扩展和该类同时被编译)。

  • 在extension里面只能写定义,不能写实现。
  • 通过扩展可以控制默写函数是否堆外界可见。
  • 扩展还可以定义属性(@property)
示例程序:

Student.h

#import <Foundation/Foundation.h>

typedef enum : NSUInteger { Female, Male, } Gender; @interface Student : NSObject -(void)sayHello; @property (readonly) Gender gender; @end 

Student.m


#import "Student.h"
#import "Student_Ext.h"
@implementation Student -(void)sayHello{ NSLog(@"Student say hello"); self.gender = Female; } -(void)sayHi{ NSLog(@"Student say Hi"); } @end 

Student_SayHi.h

#import "Student.h"

@interface Student () -(void)sayHi; @property (readwrite)Gender gender; @end 

main.m

#import <Foundation/Foundation.h>
#import "Student.h"
#import "Student_Ext.h" int main(int argc, const char * argv[]) { @autoreleasepool { Student *s =[[Student alloc] init]; [s sayHello]; [s sayHi]; } return 0; } 
category和extension

category是用来扩展累的功能的,而extension仅仅扩展定义,没有源代码的话是不能使用扩展的。

参考资料:
自定义现有的类 - Customizing Existing Classes

类扩展(class extension)

转载于:https://www.cnblogs.com/Free-Thinker/p/10797365.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值