其他分享
首页 > 其他分享> > Objective-C 之Extension

Objective-C 之Extension

作者:互联网

Objective-C 之Extension

class extension:类扩展

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

示例程序:

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)

标签:Extension,extension,void,扩展,Student,Objective,import,sayHi
来源: https://www.cnblogs.com/Free-Thinker/p/10797365.html