zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    学习进度笔记
    学习进度笔记
    学习进度笔记
    《一级架构师》阅读笔记
    学习进度笔记
    学习进度笔记
    学习进度笔记
    mysql
    error: 'wblog/' does not have a commit checked out
    有用的网页
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/10797365.html
Copyright © 2011-2022 走看看