ocruntime

原作: http://www.jianshu.com/p/25a319aee33d 

三种方法的选择

Runtime提供三种方式来将原来的方法实现代替掉,那该怎样选择它们呢?

  • Method Resolution:由于Method Resolution不能像消息转发那样可以交给其他对象来处理,所以只适用于在原来的类中代替掉。
  • Fast Forwarding:它可以将消息处理转发给其他对象,使用范围更广,不只是限于原来的对象。
  • Normal Forwarding:它跟Fast Forwarding一样可以消息转发,但它能通过NSInvocation对象获取更多消息发送的信息,例如:target、selector、arguments和返回值等信息。

Associated Objects

当使用Category对某个类进行扩展时,有时需要存储属性,Category是不支持的,这时需要使用Associated Objects来给已存在的类Category添加自定义的属性。Associated Objects提供三个API来向对象添加、获取和删除关联值:

  • void objc_setAssociatedObject (id object, const void *key, id value, objc_AssociationPolicy policy )
  • id objc_getAssociatedObject (id object, const void *key )
  • void objc_removeAssociatedObjects (id object )

其中objc_AssociationPolicy是个枚举类型,它可以指定Objc内存管理的引用计数机制。

[cpp] view plaincopy
 
  1. typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {  
  2.     OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */  
  3.     OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object.  
  4.                                             *   The association is not made atomically. */  
  5.     OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied.  
  6.                                             *   The association is not made atomically. */  
  7.     OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object. 
  8.                                             *   The association is made atomically. */  
  9.     OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied. 
  10.                                             *   The association is made atomically. */  
  11. };  

下面有个关于NSObject+AssociatedObject Category添加属性associatedO

原文地址:https://www.cnblogs.com/wcLT/p/5660533.html