iOS category add attribute

Posted by zysac on Wed, 01 Jan 2020 21:28:37 +0100

We can add attributes to iOS classification through runtime

To add attributes, remember a few keywords, 1

1. First, we use @ property to declare a property in. h like a normal class
    ///xxx+CH.h. here is the. H file of CH classification of xxx class
    @interface xxx (CH)

    @property (nonatomic ,strong) NSString *name;

    @end

At this point, two warnings appear in. m

    Property 'name' requires method 'name' to be defined - use @dynamic or provide a method implementation in this category
    Property 'name' requires method 'setName:' to be defined - use @dynamic or provide a method implementation in this category

At this time, we use @ dynamic in. m to modify the attribute name without warning

    //xxx+CH.m
    @implementation xxx (CH)

    @dynamic name;

    @end

2. Use the method of runtime to dynamically bind properties. (override the get set method)

    ///1.
    //xxx+CH.m
    #import <objc/runtime.h>///Remember to import objc/runtime.h

    @implementation xxx (CH)

    @dynamic name;

    /// name's key
    static char *nameKey = "nameKey";

    - (void)setName:(NSString *)name {
        objc_setAssociatedObject(self, nameKey, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    - (NSString *)name {
        id name = objc_getAssociatedObject(self, nameKey);
        if (name) {
            return name;
        } else {
            return @"";
        }
    }

    @end

So far, we have added properties to the classification

Note:
1. What are the types of objects

    typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
    OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */
    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.
                                            *   The association is made atomically. */
    OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.
                                            *   The association is made atomically. */
};

2. Value of non object type. We can use getValue of id to get value and return

    example: Here we take oneCGRectvalue
    - (CGRect)rect {
        id rectResult = objc_getAssociatedObject(self, rectKey);
        if (rect) {
            CGRect rect;
            [rectResult getValue:&rect];
            return rect;
        } else {
            return CGRectZero;
        }
    }

Topics: iOS Attribute