您好,登錄后才能下訂單哦!
最近一段時(shí)間在研究OC的運(yùn)行時(shí)機(jī)制,碰到一個(gè)叫property_getAttributes函數(shù),再此對(duì)其用法進(jìn)行簡(jiǎn)單的總結(jié)。
property_getAttributes主要用于獲取一個(gè)類(lèi)的property即該property的屬性數(shù)據(jù),也叫metadata(元數(shù)據(jù)),涉及到得運(yùn)行時(shí)函數(shù)包括class_copyPropertyList,property_getName和propert_getAttributes
大體用法如下:
#import <objc/runtime.h> ...... - (void)custom{ unsigned pCount; objc_property_t *properties=class_copyPropertyList([self class], &pCount);//屬性數(shù)組 for(int i=0;i<pCount;++i){ objc_property_t property=properties[i]; NSLog(@"propertyName:%s",property_getName(property)); NSLog(@"propertyAttributes:%s",property_getAttributes(property)); } }
具體用法如下:
eg.定義了一個(gè)類(lèi)CustomClass,有屬性定義如下
頭文件:
CustomClass.h #import <objc/runtime.h> ...... @property (nonatomic, strong)NSString *myName;
實(shí)現(xiàn)文件:
CustomClass.m @synthesize myName; - (void)printAllAttributes{ unsigned pCount; objc_property_t *properties=class_copyPropertyList([self class], &pCount);//屬性數(shù)組 for(int i=0;i<pCount;++i){ objc_property_t property=properties[i]; NSLog(@"propertyName:%s",property_getName(property)); NSLog(@"propertyAttributes:%s",property_getAttributes(property)); } }
最后的輸出結(jié)果如下:
2015-08-12 12:56:45.147 UIMenuController[1924:146558] propertyName:myName
2015-08-12 12:56:45.147 UIMenuController[1924:146558] propertyAttributes:T@"NSString",&,N,VmyName
解釋?zhuān)?/b>
在上例中獲得propertyAttributes為:T@"NSString",&,N,VmyName
這是一個(gè)char *類(lèi)型.
T:開(kāi)頭字母
@"NSString":property的類(lèi)型。@表示此property是OC類(lèi),"NSString"表明具體的OC類(lèi)名。例如:
id myName;//@
UIColor *myName;//@"UIColor"
UITextField *myName;//@"UITextField"
CustomClass *myName;//@"CustomClass",為自定義類(lèi)型
int myName;//i,即若為基本數(shù)據(jù)類(lèi)型,則只是@encode(int)的值i
&:表明property為retain(strong),除此之外,C表示copy,assign沒(méi)有表示。
N:表示nonatomic,若為atomic則不寫(xiě)。
VmyName:V開(kāi)頭加property名
此外,讀寫(xiě)屬性:readonly表示為R,readwrite不寫(xiě)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。