标签:associated category ios property
奇技淫巧 指过于奇巧而无益的技艺与制品.
转载请注明出处 http://blog.csdn.net/uxyheaven/article/details/46789065
众所周知,一般的情况下我们是没办法在category里加属性的.
如果想加,需要用到Associated.
@interface NSObject (XYFlyweightTransmit)
@property (nonatomic, strong) id uxy_flyweightData;
@end
@implementation NSObject (UXYFlyweightTransmit)
- (id)uxy_flyweightData
{
return objc_getAssociatedObject(self, NSObject_key_flyweightData);
}
- (void)setUxy_flyweightData:(id)flyweightData
{
objc_setAssociatedObject(self, NSObject_key_flyweightData, flyweightData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end;
如果每次需要写这么多代码才可以实现, 确实很繁琐.
一般我们会按照下面的代码封装一下
@interface NSObject (XY_associated)
- (id)uxy_getAssociatedObjectForKey:(const char *)key;
- (id)uxy_retainAssociatedObject:(id)obj forKey:(const char *)key;
- @end
@implementation NSObject (XY_associated)
- (id)uxy_getAssociatedObjectForKey:(const char *)key
{
const char * propName = key;
id currValue = objc_getAssociatedObject( self, propName );
return currValue;
}
- (id)uxy_retainAssociatedObject:(id)obj forKey:(const char *)key;
{
const char * propName = key;
id oldValue = objc_getAssociatedObject( self, propName );
objc_setAssociatedObject( self, propName, obj, OBJC_ASSOCIATION_RETAIN_NONATOMIC );
return oldValue;
}
这样,我们只需要按照如下方式添加一个属性
- (UIView *)overlay
{
return [self uxy_getAssociatedObjectForKey:"xy.navigationBar.overlay"];
}
- (void)setOverlay:(UIView *)overlay
{
[self uxy_retainAssociatedObject:overlay forKey:"xy.navigationBar.overlay"];
}
上面的代码看起来还是有不少重复的地方, 我们在用一个宏来封装一下.
可是当我们真正写宏的时候就发现get方法好写, set方法无从下手, 因为后面是跟的一个大写的字母.
一般用下面的不漂亮的方法解决:
* 约定属性用大写字母开头
* 约定下划线开头
* 写宏的时候吧setName名字传进去
不过,本文的标题既然叫奇技淫巧,用的的当然不是上述的方法.
先来看下代码表现起来是怎样的
@interface UINavigationBar (XY)
uxy_property_as_associated_strong(id, test2);
@end
@implementation UINavigationBar (XY)
uxy_property_def_associated_strong(id, test2)
@end
{
self.test2 = @"a";
id c = self.test2;
NSLog(@"%@", c);
}
实现思路:
在申明属性的时候用setter来修改属性的set方法,在前面加 __ 避开大小写.
具体实现代码如下:
#define uxy_property_as_associated_strong( __type, __name) \
@property (nonatomic, strong, setter=set__##__name:, getter=__##__name) __type __name;
#define uxy_property_def_associated_strong( __type, __name) \
- (__type)__##__name \
{ return [self uxy_getAssociatedObjectForKey:#__name]; } \
- (void)set__##__name:(id)__##__name \
{ [self uxy_retainAssociatedObject:__##__name forKey:#__name]; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
Objective-C 奇技淫巧--用来在category里加属性的宏
标签:associated category ios property
原文地址:http://blog.csdn.net/uxyheaven/article/details/46789065