码迷,mamicode.com
首页 > 其他好文 > 详细

OC Category 使用举例

时间:2015-08-05 10:49:39      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

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


OC Category 使用举例

标签:

原文地址:http://my.oschina.net/u/255456/blog/487901

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!