我們剛學習OC的時候知道類目是不可以添加屬性的,其實這不是絕對的,我們可以通過objc_setAssociatedObject動態添加屬性,和類進行關聯,那麼首先了解下什麼是關聯:
關聯是指把兩個對象相互關聯起來,使得其中的一個對象作爲另外一個對象的一部分。
關聯特性只有在Mac OS X V10.6以及以後的版本上纔是可用的。
在類的定義之外爲類增加額外的存儲空間
使用關聯,我們可以不用修改類的定義而爲其對象增加存儲空間。這在我們無法訪問到類的源碼的時候或者是考慮到二進制兼容性的時候是非常有用。關聯是基於關鍵字的,因此,我們可以爲任何對象增加任意多的關聯,每個都使用不同的關鍵字即可。關聯是可以保證被關聯的對象在關聯對象的整個生命週期都是可用的(在垃圾自動回收環境下也不會導致資源不可回收)。
創建關聯
創建關聯要使用到Objective-C的運行時函數:objc_setAssociatedObject來把一個對象與另外一個對象進行關聯。該函數需要四個參數:源對象,關鍵字,關聯的對象和一個關聯策略。當然,此處的關鍵字和關聯策略是需要進一步討論的。■ 關鍵字是一個void類型的指針。每一個關聯的關鍵字必須是唯一的。通常都是會採用靜態變量來作爲關鍵字。
■ 關聯策略表明了相關的對象是通過賦值,保留引用還是複製的方式進行關聯的;還有這種關聯是原子的還是非原子的。這裏的關聯策略和聲明屬性時的很類似。這種關聯策略是通過使用預先定義好的常量來表示的。
下面的代碼展示瞭如何把一個字符串關聯到一個數組上。
- static char overviewKey;
- NSArray * array =[[NSArray alloc] initWidthObjects:@"One", @"Two", @"Three", nil];
- //爲了演示的目的,這裏使用initWithFormat:來確保字符串可以被銷燬
- NSString * overview = [[NSString alloc] initWithFormat:@"@",@"First three numbers"];
- objc_setAssociatedObject(array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);
- [overview release];
- //(1) overview仍然是可用的
- [array release];
- //(2)overview 不可用
獲取相關聯的對象
獲取相關聯的對象時使用Objective-C函數objc_getAssociatedObject。接着上面列表7-1的代碼,我們可以使用如下代碼來獲取與array相關聯的字符串:- NSString * associatedObject = (NSString *)objc_getAssociatedObject(array, &oveviewKey);
斷開關聯
斷開關聯是使用objc_setAssociatedObject函數,傳入nil值即可。接着列表7-1中的程序,我們可以使用如下的代碼來斷開字符串overview和arry之間的關聯:
- objc_setAssociatedObject(array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN);
使用函數objc_removeAssociatedObjects可以斷開所有關聯。通常情況下不建議使用這個函數,因爲他會斷開所有關聯。只有在需要把對象恢復到“原始狀態”的時候纔會使用這個函數。
一個完整的實例程序
下面的程序綜合了前面的代碼.- #import <Foundation/Foundation.h>
- #import <objc/runtime.h>
- int main(int argc, const char* argv[])
- {
- NSAutoreleasePool * pool = [[NSAutoreleasePool] alloc init];
- static char overviewKey;
- NSArray *array =[[NSArray alloc] initWidthObjects:@"One", @"Two", @"Three", nil];
- //爲了演示的目的,這裏使用initWithFormat:來確保字符串可以被銷燬
- NSString * overview = [[NSString alloc] initWithFormat:@"@",@"First three numbers"];
- objc_setAssociatedObject(array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);
- [overview release];
- NSString *associatedObject = (NSString *)objc_getAssociatedObject(arrray, &overviewKey);
- NSLog(@"associatedObject:%@", associatedObject);
- objc_setAssociatedObject(array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN);
- [array release];
- [pool drain];
- return 0;
- }
1. 給NSObject類動態添加屬性
- @interface UIWebView (LoadProgress)
- @property (nonatomic, assign) NSInteger resourceCount;
- @end
m實現部分
首先要定義一個全局的key
- // resourceCount object keys
- static void *s_resourceCountKey = &s_resourceCountKey;
- //static void *s_resourceCountKey = "s_resourceCountKey";
初始
- @implementation UIWebView (LoadProgress)
- @dynamic resourceCount;
實現
- #pragma mark Accessors and mutators
- - (NSInteger)resourceCount
- {
- NSNumber *resourceCountNumber = objc_getAssociatedObject(self, s_resourceCountKey);
- if (! resourceCountNumber)
- {
- return 0;
- }
- else
- {
- return [resourceCountNumber integerValue];
- }
- }
- - (void)setResourceCount:(NSInteger)rCount
- {
- objc_setAssociatedObject(self, s_resourceCountKey, [NSNumber numberWithInteger:rCount], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
- }
這樣就可以直接使用了
webView.resourceCount = 10;
3. 替換或變更NSObject類方法Method
基本替換方法
- // 替換類方法
- // frome: CoconutKit
- IMP HLSSwizzleClassSelector(Class clazz, SEL selector, IMP newImplementation)
- {
- // Get the original implementation we are replacing
- Class metaClass = objc_getMetaClass(class_getName(clazz));
- Method method = class_getClassMethod(metaClass, selector);
- IMP origImp = method_getImplementation(method);
- if (! origImp) {
- return NULL;
- }
- class_replaceMethod(metaClass, selector, newImplementation, method_getTypeEncoding(method));
- return origImp;
- }
- // 替換實例方法
- IMP HLSSwizzleSelector(Class clazz, SEL selector, IMP newImplementation)
- {
- // Get the original implementation we are replacing
- Method method = class_getInstanceMethod(clazz, selector);
- IMP origImp = method_getImplementation(method);
- if (! origImp) {
- return NULL;
- }
- class_replaceMethod(clazz, selector, newImplementation, method_getTypeEncoding(method));
- return origImp;
- }
新方法定義
- // Original implementation of the methods we swizzle
- static id (*s_UIWebView__identifierForInitialRequest_Imp)(id, SEL, id, id, id) = NULL;
- // Swizzled method implementations
- static id swizzled_UIWebView__identifierForInitialRequest_Imp(UIWebView *self, SEL _cmd, id webView, id initialRequest, id dataSource);
方法初始化需要寫在類方法+ (void)load中
- + (void)load
- {
- s_UIWebView__identifierForInitialRequest_Imp = (id (*)(id, SEL, id, id, id))HLSSwizzleSelector(self, @selector(webView:identifierForInitialRequest:fromDataSource:), (IMP)swizzled_UIWebView__identifierForInitialRequest_Imp);
- }
實現部分
- #pragma mark Swizzled method implementations
- static id swizzled_UIWebView__identifierForInitialRequest_Imp(UIWebView *self, SEL _cmd, id webView, id initialRequest, id dataSource)
- {
- // 調用原方法
- (*s_UIWebView__identifierForInitialRequest_Imp)(self, _cmd, webView, initialRequest, dataSource);
- [self setResourceCount:self.resourceCount+1];
- return [NSNumber numberWithInteger:self.resourceCount];
- }
- // [self implementsProtocol:@protocol(UIActionSheetDelegate)]
- // frome: CoconutKit
- - (BOOL)implementsProtocol:(Protocol *)protocol
- {
- // Only interested in optional methods. Required methods are checked at compilation time
- unsigned int numberOfMethods = 0;
- struct objc_method_description *methodDescriptions = protocol_copyMethodDescriptionList(protocol, NO /* optional only */, YES, &numberOfMethods);
- for (unsigned int i = 0; i < numberOfMethods; ++i) {
- struct objc_method_description methodDescription = methodDescriptions[i];
- SEL selector = methodDescription.name;
- if (! class_getInstanceMethod([self class], selector)) {
- NSString *selectorString = [NSString stringWithCString:sel_getName(selector) encoding:NSUTF8StringEncoding];
- NSString *protocolName = [NSString stringWithCString:protocol_getName(protocol) encoding:NSUTF8StringEncoding];
- HLSLoggerInfo(@"Class %@ does not implement method %@ of protocol %@", [self className], selectorString, protocolName);
- selectorString = nil; // Just to remove unused variable warnings
- protocolName = nil;
- return NO;
- }
- }
- return YES;
- }