想到要如何為所有的對象增加執行個體變數嗎? 使用Category可以很方便地為現有的類增加方法,但卻無法直接增加執行個體變數(有為此使用查表法的,也算曲線救國吧)。不過從Mac OS X v10.6開始,系統提供了Associative References,這個問題就很容易解決了。
我根據Objective-C Reference中的樣本修改了一下,直接上代碼了。重點是其中objc_setAssociatedObject的使用, 並且其中Key是一個地址,而不是字串。
#import <Foundation/Foundation.h>#import <objc/runtime.h> int main (int argc, const char * argv[]) { @autoreleasepool {/*Seciton 0. 關聯資料的Key和Value*/ static char overviewKey;static const char *myOwnKey = "VideoProperty\0";static const char intValueKey = 'i'; NSArray *array = [[NSArray alloc] initWithObjects:@ "One", @"Two", @"Three", nil]; // For the purposes of illustration, use initWithFormat: to ensure // we get a deallocatable string NSString *overview = [[NSString alloc] initWithFormat:@"%@", @"First three numbers"];NSString *videoKeyValue = @"This is a video";NSNumber *intValue = [[NSNumber alloc]initWithInt:5];/*Section 1. 關聯資料設定部分*/ objc_setAssociatedObject ( array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN ); [overview release];objc_setAssociatedObject ( array, myOwnKey, videoKeyValue, OBJC_ASSOCIATION_RETAIN);objc_setAssociatedObject ( array, &intValueKey, intValue, OBJC_ASSOCIATION_RETAIN); /*Section 3. 關聯資料查詢部分*/ NSString *associatedObject = (NSString *) objc_getAssociatedObject (array, &overviewKey); NSLog(@"associatedObject: %@", associatedObject);NSString *associatedObject2 = (NSString *) objc_getAssociatedObject(array, myOwnKey);NSLog(@"Video Key value is %@", associatedObject2);NSString *assObject3 = (NSString *) objc_getAssociatedObject(array, &myOwnKey);if( assObject3 ){NSLog(@"不會進入這裡! assObject3 應當為nil!");}else{NSLog(@"OK. 通過myOwnKey的地址是得不到資料的!");} NSNumber *assKeyValue = (NSNumber *) objc_getAssociatedObject(array, &intValueKey); NSLog(@"Int value is %d",[assKeyValue intValue]);/*Section 3. 關聯資料清理部分*/ objc_setAssociatedObject ( array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN );objc_setAssociatedObject ( array, myOwnKey, nil, OBJC_ASSOCIATION_ASSIGN);objc_setAssociatedObject ( array, &intValueKey, nil, OBJC_ASSOCIATION_ASSIGN); [array release]; } return 0;}
*可以使用如下指令在命令列下編譯:
clang -o associates -g -x objective-c++ -Wall associates.mm -framework Foundation -lobjc