iOS 類擴(kuò)展和分類(類別)

#import "secondViewController.h"
#import <objc/runtime.h>

/**
 類擴(kuò)展,可以增加成員變量、屬性、方法
 */
@interface secondViewController ()
- (void)reset1;
@end

/**
  分類或者類別。只能增加方法,不能增加成員變量、屬性(其實也是可以加的,利用通過runtime解決無setter/getter的問題而已,_成員變量依然報錯)
  原因:分類的指針結(jié)構(gòu)體中,根本沒有屬性列表,只有方法列表
 */
@interface secondViewController (category)
@property(nonatomic,copy) NSString *name;
- (void)reset;
@end

@implementation secondViewController (category)

static NSString *nameWithSetterGetterKey = @"nameWithSetterGetterKey";   //定義一個key值
//運行時實現(xiàn)setter方法
- (void)setName:(NSString *)nameWithSetterGetter {
    objc_setAssociatedObject(self, &nameWithSetterGetterKey, nameWithSetterGetter, OBJC_ASSOCIATION_COPY);
}
//運行時實現(xiàn)getter方法
- (NSString *)name{
    return objc_getAssociatedObject(self, &nameWithSetterGetterKey);
}

- (void)reset{
    NSLog(@"響應(yīng)了分類中的方法");
}
@end

@implementation secondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor systemGreenColor];
    
    self.name = @"hahhaa";
    [self reset];
    [self reset1];
}


- (void)reset1{
    NSLog(@"響應(yīng)了類擴(kuò)展中的方法");
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容