iOS 扩展机制category与associative

来源:互联网 发布:苹果电脑mac使用技巧 编辑:程序博客网 时间:2024/06/01 08:28
在写新浪微博的时候,要处理点击微博图片放大的问题,这里我采用的处理是使用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的头文件:

#import <UIKit/UIKit.h>    @interface UIImageView (associate)    @property(nonatomic,strong)NSString* myString;    -(void)Output; @end 

category的实现文件:

#import <objc/runtime.h>  #import "UIImageView+associate.h"    static void * MyKey = (void *)@"MyKey";    @implementation UIImageView (associate)    -(NSString*)myString {      return objc_getAssociatedObject(self, MyKey);  }    -(void)setMyString:(NSString *)string {      objc_setAssociatedObject(self, MyKey, string, OBJC_ASSOCIATION_COPY_NONATOMIC);  }    -(void)Output {      NSLog(@"output mystring:%@",self.myString);  }  @end  


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

测试一下:

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

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

0 0
原创粉丝点击