博客> 类扩展属性--不受本来的约束
类扩展属性--不受本来的约束
2018-12-15 01:39 评论:0 阅读:492 阮延超
属性 类扩展

在IOS的官方文档中,类扩展是不能对属性进行扩展的,但是天无绝人之路,在掌握了runtime的运行机制之后,我们可以机智的用assocaite来扩展类的属性。必须使用,使用objc_getAssociatedObject,objc_setAssociatedObject以及objc_removeAssociatedObjects。

  • 官方文档说明如下 /**
  • Sets an associated value for a given object using a given key and association policy.
  • @param object The source object for the association.
  • @param key The key for the association.
  • @param value The value to associate with the key key for object. Pass nil to clear an existing association.
  • @param policy The policy for the association. For possible values, see “Associative Object Behaviors.”
  • @see objc_setAssociatedObject
  • @see objc_removeAssociatedObjects / OBJC_EXPORT void objc_setAssociatedObject(id object, const void key, id value, objc_AssociationPolicy policy) OSX_AVAILABLE_STARTING(MAC_10_6, __IPHONE_3_1); /**
  • Returns the value associated with a given object for a given key.
  • @param object The source object for the association.
  • @param key The key for the association.
  • @return The value associated with the key \e key for \e object.
  • @see objc_setAssociatedObject / OBJC_EXPORT id objc_getAssociatedObject(id object, const void key) OSX_AVAILABLE_STARTING(MAC_10_6, __IPHONE_3_1); /**
  • Removes all associations for a given object.
  • @param object An object that maintains associated objects.
  • @note The main purpose of this function is to make it easy to return an object
  • to a "pristine state”. You should not use this function for general removal of
  • associations from objects, since it also removes associations that other clients
  • may have added to the object. Typically you should use \c objc_setAssociatedObject
  • with a nil value to clear an association.
  • @see objc_setAssociatedObject
  • @see objc_getAssociatedObject */ OBJC_EXPORT void objc_removeAssociatedObjects(id object) OSX_AVAILABLE_STARTING(MAC_10_6, __IPHONE_3_1);

举例说明怎么完成类属性的扩展吧

  • 先创建一个person类

    import

        @interface Person : NSObject
        @property (nonatomic, copy) NSString *name;
        @end
        #import "Person.h"
        @implementation Person
        @end
  • 新建一个分类,运用associative添加属性

    import "Person.h"

        @interface Person (addproty)
        @property(nonatomic, copy)NSString *addr;
        @end
        #import "Person+addproty.h"
        #import <objc>
        @implementation Person (addproty)
        static char strAddrKey = 'a';
        - (NSString *)addr
        {
                return objc_getAssociatedObject(self, &strAddrKey);
        }
        - (void)setAddr:(NSString *)addr
        {
                objc_setAssociatedObject(self, &strAddrKey, addr, OBJC_ASSOCIATION_COPY_NONATOMIC);
        }
        @end
收藏
0
sina weixin mail 回到顶部