iOS 扩展机制category与associative

在写新浪微博的时候,要处理点击微博图片放大的问题,这里我采用的处理是使用category和associative扩展机制为UIImageview扩展添加一个方法和一个属性,这个方法是处理点击图片放大,而这个属性就是这个图片的下载链接地址URL。


下面稍微解说一下这两个扩展机制:

category和associative作为objective-c 扩展机制的两个特性,category可以通过它来扩展方法;associative可以通过它来扩展属性。

在iOS开发过程中,前者category比较常见,也比较简单,这里就不说了,这里主要说一下associative;

后者associative相对用的就比较少,要用associative就必须使用#import<objc/runtime.h>,然后调用objc_setAssociatedObject 和 objc_getAssociatedObject  方法分别为属性添加setter 和  getter方法,就可以实现属性扩展了。


下面介绍一下这两个方法:

①:void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)

其中的参数分别是:

Parameters

object:  The source object for the association.

key: The key for the association.

value:  The value to associate with the key key for object. Pass nil to clear an existing association.

policy:  The policy for the association

其中的policy有

enum {

   OBJC_ASSOCIATION_ASSIGN = 0,

   OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,

   OBJC_ASSOCIATION_COPY_NONATOMIC = 3,

   OBJC_ASSOCIATION_RETAIN = 01401,

   OBJC_ASSOCIATION_COPY = 01403

};

②:id objc_getAssociatedObject(id object, void *key)

Parameters

object:  The source object for the association.

key:  The key for the association.

Return Value

The value associated with the key key for object.


都比较简单,下面就通过一个demo来说明吧!

我这里是扩展UIImageview为其添加一个方法和一个属性。

category的头文件:

[cpp]  view plain copy
  1. #import <UIKit/UIKit.h>  
  2.   
  3. @interface UIImageView (associate)  
  4.   
  5. @property(nonatomic,strong)NSString* myString;  
  6.   
  7. -(void)Output;  
  8.   
  9. @end  


category的实现文件:

[cpp]  view plain copy
  1. #import <objc/runtime.h>  
  2. #import "UIImageView+associate.h"  
  3.   
  4. static void * MyKey = (void *)@"MyKey";  
  5.   
  6. @implementation UIImageView (associate)  
  7.   
  8. -(NSString*)myString {  
  9.     return objc_getAssociatedObject(self, MyKey);  
  10. }  
  11.   
  12. -(void)setMyString:(NSString *)string {  
  13.     objc_setAssociatedObject(self, MyKey, string, OBJC_ASSOCIATION_COPY_NONATOMIC);  
  14. }  
  15.   
  16. -(void)Output {  
  17.     NSLog(@"output mystring:%@",self.myString);  
  18. }  
  19. @end  
  20.   
  21.       

说明:头文件中添加了一个属性和一个方法,在实现文件中使用associative特性为属性重写了setter和getter方法,都比较简单。

测试一下:

[cpp]  view plain copy
  1. UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Icon@2x.png"]];  
  2.     imageView.bounds = CGRectMake(50, 50, 100, 100);  
  3.     imageView.myString = @"hello world";  
  4.     [self.view addSubview:imageView];      
  5.     [imageView Output];  

运行后,模拟器上就显示一个图片,终端输出:output mystring:hello world

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值