category中增加一个属性(需要显式生命存取方法,不生成成员变量)
#import <Foundation/Foundation.h> #import "UTShareContent.h" @interface UTShareContent (ItemID) @property (nonatomic, strong) NSString *itemId; @end
runtime 保存属性的数据,需要引入<objc/runtime.h>:
使用 objc_setAssociatedObject 和 objc_getAssociatedObject 方法:
/** * 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);
这里使用 @selector(itemId) 只是提供一个const void * 类型的key, 使用其他指针也可以(比如字符串),只要保证在这个类中唯一:
#import "UTShareContent+ItemId.h" #import <objc/runtime.h> @implementation UTShareContent(ItemID) //@dynamic itemId; -(NSString *)itemId{ return objc_getAssociatedObject(self, @selector(itemId)); } -(void)setItemId:(NSString *)itemId{ objc_setAssociatedObject(self, @selector(itemId), itemId, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end
时间: 2024-10-31 06:36:07