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)