iOS 動態添加屬性方法

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

 

寫在前面:

  動態增加屬性也不是很肆意的增加,是需要代碼進行寫的。如果一個類沒有那個屬性,那麼在編譯階段就會報錯而導致無法進行。之所以還叫做動態添加大致上是因為可以不重寫某個類,而進行相應的屬性的添加吧!不扯那麼多了。切入正題:

   首先需要建立類別,用來寫入相應的set/get方法。

#import <UIKit/UIKit.h>@interface UILabel (Associate)- (void) setFlashColor:(UIColor *) flashColor;- (UIColor *) getFlashColor;@end
UILabel+Associate.h

  重點來了,實現:

#import "UILabel+Associate.h"#import <objc/runtime.h>@implementation UILabel (Associate)static char flashColorKey;- (void) setFlashColor:(UIColor *) flashColor{    objc_setAssociatedObject(self, &flashColorKey, flashColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}- (UIColor *) getFlashColor{   return objc_getAssociatedObject(self, &flashColorKey);}@end
UILabel+Associate.m

  調用:

UILabel *lab = [[UILabel alloc] init];    [lab setFlashColor:[UIColor redColor]];    NSLog(@"%@", [lab getFlashColor]);
View Code

  由此可見:使用runtime進行屬性的添加實際上是通過“OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)”進行添加的。

  一個純C的方法,傳入一個OC的對象,根據一個Key設定一個Value,這就是整個的方法。

思考:

  。。。總覺得那個C函數的實現裡面有個大容器。。。(僅為個人想的。。)

 

註:代碼來自http://www.cnblogs.com/luoguoqiang1985/p/3551966.html

    

 

iOS 動態添加屬性方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.