2011-12-13 70 views
3

我想擴展UIView類以包含setUserData方法,它將保存對象值或任何值。這是聲明:UIView類別和屬性

userData被定義爲.h文件中的id屬性。

@implementation UIView (Extensions) 

@synthesize userData; 

-(void) setUserData:(id)value 
{ 
    self.userData = value; 
} 

@end 

當然xCode抱怨說我不能在類別中使用@synthesize。我該如何實現這個任務,或者UIView中已經有一些可以容納一個對象的屬性。就像標籤屬性一樣,但標籤屬性只包含整合。

+0

可能重複(http://stackoverflow.com/questions/8492602/adding-properties-to-uicontrols-without-subclassing) – Caleb 2011-12-13 17:20:40

回答

5

如您所述,您無法綜合分類中的屬性。要達到這個目標,你必須使用一個名爲關聯對象的Obj-C運行時功能。的[添加屬性到UIControls沒有子]

#import <objc/runtime.h> 

const char * const viewKey = "jweinberg.view.storage"; 

@implementation UIView (Storage) 

- (id)myProperty; 
{ 
    return objc_getAssociatedObject(self, viewKey); 
} 

- (void)setMyProperty:(id)property; 
{ 
    objc_setAssociatedObject(self, viewKey, property, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
}