现在的位置: 首页 > 综合 > 正文

iOS 扩展机制category与associative

2018年05月12日 ⁄ 综合 ⁄ 共 2060字 ⁄ 字号 评论关闭

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的头文件:

  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的实现文件:

  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方法,都比较简单。

测试一下:

  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

抱歉!评论已关闭.