為類添加執行個體變數 (Associative References)

來源:互聯網
上載者:User

在object-c中我們知道可以使用categories來為擴充類方法(比如我們可以為系統的類添加自己的方法)

例如:我們要想在每個NSString前面添加一個

@interface NSString ( CategoryName )

// method declarations

- (NSString *) getNSString;

@end

@implementation NSString ( CategoryName )

// method definitions

- (NSString *)getNSString

{

    return  [NSString stringWithFormat:@"hello+%@", self];

}

@end

 調用方法如下:

NSString *str =
@"world";

NSLog(@"str == [%@]",
[str getNSString]);

列印出來的結果:str == [hello+world]

我們知道Categories可以為類擴充自己的方法,但是如何添加屬性呢?

例如我們如何為NSString添加一個tag的屬性(我們可以用Associative)

********************************************************************

Associative references are available only in iOS and in Mac OS X v10.6 and later

********************************************************************

#import
<objc/runtime.h>

@interface NSString(categories)

@property(nonatomic,retain)
id objectTag;

- (NSString *)getNSString;

@end

static
const char *ObjectTagKey =
"ObjectTag";

@implementation NSString(categories)

@dynamic objectTag;  

- (id)objectTag {  

   
return
objc_getAssociatedObject(self,
ObjectTagKey);  

}  

- (void)setObjectTag:(id)newObjectTag {  

   
objc_setAssociatedObject(self,
ObjectTagKey, newObjectTag,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);  

}  

- (NSString *)getNSString

{

   
return  [NSString
stringWithFormat:@"%@+hello",
self];

}

@end

NSString *str =
@"world";

NSLog(@"str == [%@]",
[str getNSString]);

str.objectTag = [NSNumber
numberWithInt:7];//對objectTag設定NSMunber類型的值

NSLog(@"str.objectTag===[%@],object class
=== [%@]", str.objectTag, [str.objectTag
class]);

str.objectTag =
@"5";//對objectTag設定NSString類型的值

NSLog(@"str.objectTag===[%@],object class
=== [%@]", str.objectTag, [str.objectTag
class]);

str.objectTag =
nil;//對objectTag設定為nil,當然我們也可以用objc_removeAssociatedObjects

NSLog(@"str.objectTag===[%@],object class
=== [%@]", str.objectTag, [str.objectTag
class]);

列印結果

詳見官方文檔

http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/ObjectiveC/Chapters/ocAssociativeReferences.html%23//apple_ref/doc/uid/TP30001163-CH24-SW1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.