category中增長一個屬性(須要顯式生命存取方法,不生成成員變量)atom
#import <Foundation/Foundation.h> #import "UTShareContent.h" @interface UTShareContent (ItemID) @property (nonatomic, strong) NSString *itemId; @end
runtime 保存屬性的數據,須要引入<objc/runtime.h>:指針
使用 objc_setAssociatedObject 和 objc_getAssociatedObject 方法:code
/** * 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, 使用其餘指針也能夠(好比字符串),只要保證在這個類中惟一:ci
#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