objc_runtime给类目添加属性关联(objc_setAssociatedObject、objc_getAssociatedObject)

来源:互联网 发布:linux下zip解压命令 编辑:程序博客网 时间:2024/05/21 07:03

       我们刚学习OC的时候知道类目是不可以添加属性的,其实这不是绝对的,我们可以通过objc_setAssociatedObject动态添加属性,和类进行关联,那么首先了解下什么是关联:


    关联是指把两个对象相互关联起来,使得其中的一个对象作为另外一个对象的一部分。
    关联特性只有在Mac OS X V10.6以及以后的版本上才是可用的。

在类的定义之外为类增加额外的存储空间

    使用关联,我们可以不用修改类的定义而为其对象增加存储空间。这在我们无法访问到类的源码的时候或者是考虑到二进制兼容性的时候是非常有用。
    关联是基于关键字的,因此,我们可以为任何对象增加任意多的关联,每个都使用不同的关键字即可。关联是可以保证被关联的对象在关联对象的整个生命周期都是可用的(在垃圾自动回收环境下也不会导致资源不可回收)。

创建关联

    创建关联要使用到Objective-C的运行时函数:objc_setAssociatedObject来把一个对象与另外一个对象进行关联。该函数需要四个参数:源对象,关键字,关联的对象和一个关联策略。当然,此处的关键字和关联策略是需要进一步讨论的。
  ■  关键字是一个void类型的指针。每一个关联的关键字必须是唯一的。通常都是会采用静态变量来作为关键字。
  ■  关联策略表明了相关的对象是通过赋值,保留引用还是复制的方式进行关联的;还有这种关联是原子的还是非原子的。这里的关联策略和声明属性时的很类似。这种关联策略是通过使用预先定义好的常量来表示的。
    下面的代码展示了如何把一个字符串关联到一个数组上。
列表7-1 把一个字符串关联到一个数组
[cpp] view plaincopy
  1. static char overviewKey;  
  2. NSArray * array =[[NSArray alloc] initWidthObjects:@"One", @"Two", @"Three", nil];  
  3. //为了演示的目的,这里使用initWithFormat:来确保字符串可以被销毁  
  4. NSString * overview = [[NSString alloc] initWithFormat:@"@",@"First three numbers"];  
  5. objc_setAssociatedObject(array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);  
  6.   
  7. [overview release];  
  8. //(1) overview仍然是可用的  
  9.   
  10. [array release];  
  11. //(2)overview 不可用  
    在(1)处,字符串overview仍然是可用的,这是因为OBJC_ASSOCIATION_RETAIN策略指明了数组要保有相关的对象。当数组array被销毁的时候,也就是在(2)处overview也就会被释放,因此而被销毁。如果此时还想使用overview,例如想通过log来输出overview的值,则会出现运行时异常。

获取相关联的对象

    获取相关联的对象时使用Objective-C函数objc_getAssociatedObject。接着上面列表7-1的代码,我们可以使用如下代码来获取与array相关联的字符串:
[cpp] view plaincopy
  1. NSString * associatedObject = (NSString *)objc_getAssociatedObject(array, &oveviewKey);  

断开关联

    断开关联是使用objc_setAssociatedObject函数,传入nil值即可。
    接着列表7-1中的程序,我们可以使用如下的代码来断开字符串overview和arry之间的关联:
[cpp] view plaincopy
  1. objc_setAssociatedObject(array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN);  
   其中,被关联的对象为nil,此时关联策略也就无关紧要了。
    使用函数objc_removeAssociatedObjects可以断开所有关联。通常情况下不建议使用这个函数,因为他会断开所有关联。只有在需要把对象恢复到“原始状态”的时候才会使用这个函数。

一个完整的实例程序

    下面的程序综合了前面的代码.
[cpp] view plaincopy
  1. #import <Foundation/Foundation.h>  
  2. #import <objc/runtime.h>  
  3.   
  4.   
  5. int main(int argc, const char* argv[])  
  6. {  
  7.     NSAutoreleasePool * pool = [[NSAutoreleasePool] alloc init];  
  8.       
  9.     static char overviewKey;  
  10.     NSArray *array =[[NSArray alloc] initWidthObjects:@"One", @"Two", @"Three", nil];  
  11.     //为了演示的目的,这里使用initWithFormat:来确保字符串可以被销毁  
  12.     NSString * overview = [[NSString alloc] initWithFormat:@"@",@"First three numbers"];  
  13.     objc_setAssociatedObject(array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);  
  14.     [overview release];  
  15.       
  16.     NSString *associatedObject = (NSString *)objc_getAssociatedObject(arrray, &overviewKey);  
  17.     NSLog(@"associatedObject:%@", associatedObject);  
  18.       
  19.     objc_setAssociatedObject(array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN);  
  20.     [array release];  
  21.       
  22.     [pool drain];  
  23.     return 0;  
  24. }  


1. 给NSObject类动态添加属性

h定义部分
[cpp] view plaincopyprint?
  1. @interface UIWebView (LoadProgress)  
  2.   
  3. @property (nonatomic, assign) NSInteger resourceCount;  
  4.   
  5. @end  

m实现部分

首先要定义一个全局的key

[cpp] view plaincopyprint?
  1. // resourceCount object keys  
  2. static void *s_resourceCountKey = &s_resourceCountKey;  
  3. //static void *s_resourceCountKey = "s_resourceCountKey";  

初始
[cpp] view plaincopyprint?
  1. @implementation UIWebView (LoadProgress)  
  2. @dynamic resourceCount;  

实现
[cpp] view plaincopyprint?
  1. #pragma mark Accessors and mutators  
  2.   
  3. - (NSInteger)resourceCount  
  4. {  
  5.     NSNumber *resourceCountNumber = objc_getAssociatedObject(self, s_resourceCountKey);  
  6.     if (! resourceCountNumber)  
  7.     {  
  8.         return 0;  
  9.     }  
  10.     else  
  11.     {  
  12.         return [resourceCountNumber integerValue];  
  13.     }  
  14. }  
  15.   
  16. - (void)setResourceCount:(NSInteger)rCount  
  17. {  
  18.     objc_setAssociatedObject(self, s_resourceCountKey, [NSNumber numberWithInteger:rCount], OBJC_ASSOCIATION_RETAIN_NONATOMIC);  
  19. }  

这样就可以直接使用了

webView.resourceCount = 10;



2. 给NSObject类动态添加代理protocol

同属性

动态创建代理暂时先不写了


3. 替换或变更NSObject类方法Method

基本替换方法

[cpp] view plaincopyprint?
  1. // 替换类方法  
  2. // frome: CoconutKit  
  3. IMP HLSSwizzleClassSelector(Class clazz, SEL selector, IMP newImplementation)  
  4. {  
  5.     // Get the original implementation we are replacing  
  6.     Class metaClass = objc_getMetaClass(class_getName(clazz));  
  7.     Method method = class_getClassMethod(metaClass, selector);  
  8.     IMP origImp = method_getImplementation(method);  
  9.     if (! origImp) {  
  10.         return NULL;  
  11.     }  
  12.       
  13.     class_replaceMethod(metaClass, selector, newImplementation, method_getTypeEncoding(method));  
  14.     return origImp;  
  15. }  
  16.   
  17. // 替换实例方法  
  18. IMP HLSSwizzleSelector(Class clazz, SEL selector, IMP newImplementation)  
  19. {  
  20.     // Get the original implementation we are replacing  
  21.     Method method = class_getInstanceMethod(clazz, selector);  
  22.     IMP origImp = method_getImplementation(method);  
  23.     if (! origImp) {  
  24.         return NULL;  
  25.     }  
  26.       
  27.     class_replaceMethod(clazz, selector, newImplementation, method_getTypeEncoding(method));  
  28.     return origImp;  
  29. }  

新方法定义

[cpp] view plaincopyprint?
  1. // Original implementation of the methods we swizzle  
  2. static id (*s_UIWebView__identifierForInitialRequest_Imp)(id, SEL, id, id, id) = NULL;  
  3.   
  4. // Swizzled method implementations  
  5. static id swizzled_UIWebView__identifierForInitialRequest_Imp(UIWebView *self, SEL _cmd, id webView, id initialRequest, id dataSource);  

方法初始化需要写在类方法+ (void)load中
[cpp] view plaincopyprint?
  1. + (void)load  
  2. {  
  3.     s_UIWebView__identifierForInitialRequest_Imp = (id (*)(id, SEL, id, id, id))HLSSwizzleSelector(self, @selector(webView:identifierForInitialRequest:fromDataSource:), (IMP)swizzled_UIWebView__identifierForInitialRequest_Imp);  
  4. }  

实现部分
[cpp] view plaincopyprint?
  1. #pragma mark Swizzled method implementations  
  2.   
  3. static id swizzled_UIWebView__identifierForInitialRequest_Imp(UIWebView *self, SEL _cmd, id webView, id initialRequest, id dataSource)  
  4. {  
  5.     // 调用原方法  
  6.     (*s_UIWebView__identifierForInitialRequest_Imp)(self, _cmd, webView, initialRequest, dataSource);  
  7.       
  8.     [self setResourceCount:self.resourceCount+1];  
  9.       
  10.     return [NSNumber numberWithInteger:self.resourceCount];  
  11. }  


4. 代理方法检索

可直接定义到NSObject的Category中
[cpp] view plaincopyprint?
  1. // [self implementsProtocol:@protocol(UIActionSheetDelegate)]  
[cpp] view plaincopyprint?
  1. // frome: CoconutKit  
  2. - (BOOL)implementsProtocol:(Protocol *)protocol  
  3. {  
  4.     // Only interested in optional methods. Required methods are checked at compilation time  
  5.     unsigned int numberOfMethods = 0;  
  6.     struct objc_method_description *methodDescriptions = protocol_copyMethodDescriptionList(protocol, NO /* optional only */, YES, &numberOfMethods);  
  7.     for (unsigned int i = 0; i < numberOfMethods; ++i) {  
  8.         struct objc_method_description methodDescription = methodDescriptions[i];  
  9.         SEL selector = methodDescription.name;  
  10.         if (! class_getInstanceMethod([self class], selector)) {  
  11.             NSString *selectorString = [NSString stringWithCString:sel_getName(selector) encoding:NSUTF8StringEncoding];  
  12.             NSString *protocolName = [NSString stringWithCString:protocol_getName(protocol) encoding:NSUTF8StringEncoding];  
  13.             HLSLoggerInfo(@"Class %@ does not implement method %@ of protocol %@", [self className], selectorString, protocolName);  
  14.             selectorString = nil;               // Just to remove unused variable warnings  
  15.             protocolName = nil;  
  16.             return NO;  
  17.         }  
  18.     }  
  19.       
  20.     return YES;  



0 0
原创粉丝点击