iOS分類不能新增屬性原因的探索

2021-08-19 17:33:13 字數 3044 閱讀 4209

最近跟人交流時,提到乙個問題,說ios分類中不能新增屬性。這裡**一下不能新增的原因和新增的方法。

首先,建立乙個person類,**如下:

xgperson.h

#import @inte***ce xgperson : nsobject

/// 年齡

@property (nonatomic, copy) nsstring *age;

/// 性別

@property (nonatomic, copy) nsstring ****;

- (void)text1;

@end

xgperson.m

#import "xgperson.h"

@implementation xgperson

- (void)text1

- (void)text2

@end

在控制器裡獲取並列印該類的成員變數、屬性和方法,**如下:

- (void)touchesbegan:(nsset*)touches withevent:(uievent *)event 

free(ivars);

// 獲取屬性

unsigned int propertycount = 0;

objc_property_t *propertylist = class_copypropertylist([xgperson class], &propertycount);

for (int i = 0; i < propertycount; i++)

// 獲取方法列表

unsigned int methodcount = 0;

method *methods = class_copymethodlist([xgperson class], &methodcount);

for (int i = 0; i < methodcount; i++)

}

此時控制台輸出如下:

這裡需要提出的是,平時使用@property的時候,系統會自動生成帶「_」的成員變數和該變數的setter和getter方法。也就是說,屬性相當於乙個成員變數加getter和setter方法。那麼,在分類裡使用@property會是什麼樣子呢,下面來建立乙個分類:

xgperson+height.h

#import "xgperson.h"

@inte***ce xgperson (height)

@property (nonatomic, copy) nsstring *height;

@end

xgperson+height.m

#import "xgperson+height.h"

#import @implementation xgperson (height)

@end

如果像上面一樣只在.h檔案裡宣告height,那麼.m檔案裡會出現兩個警告,意思是說沒有實現setter和getter方法。

此時在控制器裡執行touchesbegan方法,控制台輸出如下:

可以看到,此時person類裡並沒有新增帶「_」的成員變數,也沒有實現setter和getter方法,只是在屬性列表裡新增了height屬性。並且此時如果在控制器裡呼叫self.height,程式執行時會報錯,顯示找不到該方法。實現一下person分類裡的兩個方法:

xgperson+height.m

#import "xgperson+height.h"

#import @implementation xgperson (height)

- (nsstring *)height

- (void)setheight:(nsstring *)height

@end

此時在控制器裡執行touchesbegan方法,控制台輸出如下:

可以看到即使實現了setter和getter方法,也仍然沒有新增帶「

」的成員變數,也就是說,在setter和getter方法裡仍然不能直接訪問以下劃線開頭的成員變數,因為在分類裡用@property宣告屬性時系統並沒有新增以「」開頭的成員變數。此時要達到新增的目的可以使用執行時的關聯物件。示例**如下:

xgperson+height.m

#import "xgperson+height.h"

#import @implementation xgperson (height)

- (nsstring *)height

- (void)setheight:(nsstring *)height

@end

當然也可以在setter和getter方法裡訪問該類其他的屬性,比如在uiview的分類的裡新增x、y屬性,可以直接返回self.frame.origin.x和self.frame.origin.y。

總結在分類裡使用@property宣告屬性,只是將該屬性新增到該類的屬性列表,並宣告了setter和getter方法,但是沒有生成相應的成員變數,也沒有實現setter和getter方法。所以說分類不能新增屬性。但是在分類裡使用@property宣告屬性後,又實現了setter和getter方法,那麼在這個類以外可以正常通過點語法給該屬性賦值和取值。就是說,在分類裡使用@property宣告屬性,又實現了setter和getter方法後,可以認為給這個類新增上了屬性。

iOS分類新增屬性

我們可以通過runtime來給ios的分類新增屬性.1.首先我們像普通的類一樣在.h裡頭使用 property宣告乙個屬性 ch.h.這裡是 類的ch分類的.h檔案 inte ce ch property nonatomic strong nsstring name end這時,m中就會出現兩個警告...

ios 分類新增屬性。

我們都知道可以通過分類新增方法,但是是否可以新增變數有一部分人就不知道了 其實分類裡面是不可以新增成員變數的,但是卻可以新增屬性。這是因為在分類中新增的屬性不會自動生成set get方法,這是就需要自己在分類的實現檔案裡面實現屬性的set get方法,如果你跟平時一樣去寫set get方法你會發現 ...

iOS 為分類新增屬性

我們知道分類可以很簡單的新增方法,但是新增屬性卻無能為力,但是我們還是可以通過動run time的associate就可以做到 比如說我要在uimage中新增乙個url屬性 h inte ce uiimage url property nonatomic,copy nsstring url end ...