1.使用关联##
关联是指把两个对象相互关联起来,使得其中的一个对象作为另一个对象的一部分。
使用关联,是基于关键字的,因此,我们可以为任意对象增加任意多的关联,但是关键字是唯一的。关联可以保证被关联对象
在关联对象
的整个生命周期都是可用的。
1.1 创建关联、获取被关联的关联对象、断开关联###
使用Objective-C中的runtime.h中
- 创建关联:objc_setAssociatedObject函数
/**
* 使用给出的关键字和关联策略来设置对象的关联值
*
* @param object 被关联对象、目标对象
* @param key 关键字
* @param value 关联对象,输入nil时候清除存在关联
* @param policy 关联策略
*/
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
//*> objc_AssociationPolicy 关联策略枚举
typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
OBJC_ASSOCIATION_ASSIGN = 0,
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
OBJC_ASSOCIATION_RETAIN = 01401,
OBJC_ASSOCIATION_COPY = 01403
};
2)获取关联:objc_getAssociatedObject函数
/**
* 通过关键字返回被关联对象的关联值
*
* @param object 被关联对象、目标对象
* @param key 关键字
*
* @return The value associated with the key e key for e object.
*/
id objc_getAssociatedObject(id object, const void *key)
3)断开关联:objc_removeAssociatedObjects函数
/**
* 移除被关联对象的所有关联
*
* @param object 被关联对象、目标对象
*
* @note The main purpose of this function is to make it easy to return an object
* to a "pristine state”. You should not use this function for general removal of
* associations from objects, since it also removes associations that other clients
* may have added to the object. Typically you should use c objc_setAssociatedObject
* with a nil value to clear an association.
*/
备注:
1.关键字:void *类型,通常使用静态变量作为关键字,例如:
static const char *associatedKeyPanGesture = "__associated_key_pangesture";
2.关联策略:objc_AssociationPolicy枚举,和类声明中修饰属性的关键字一样。有assign和retain之分,有atomically和 no atomically之分。
1.2创建关联的测试代码###
static const char * associatedKeyMyname = "_associated_key_myName";
static const char * associatiedKeyPersonalInfo = "_associated_key_personalinfomation";
//*> 关联对象
- (void)AssociationApiTest
{
//*> 把array关联到tempstring - 观察作用域
NSDictionary * infoDic = @{@"Name":@"吕洪阳",@"Age":@"23",@"Gender":@"Male"};
NSString * infoNote = @"Personal information";
objc_setAssociatedObject(infoNote, associatiedKeyPersonalInfo, infoDic, OBJC_ASSOCIATION_RETAIN);
NSDictionary * associatedInfoDic = (NSDictionary *)objc_getAssociatedObject(infoNote, associatiedKeyPersonalInfo);
NSLog(@"
%@%@",infoNote,associatedInfoDic);
//*> 把_myName关联到self - 观察作用域
_myName = @"吕洪阳";
objc_setAssociatedObject(self, associatedKeyMyname, _myName, OBJC_ASSOCIATION_RETAIN);
NSNumber * associatedName1 = (NSNumber *)objc_getAssociatedObject(self, associatedKeyMyname);
_myName = @"Steven Jobs";
NSNumber * associatedName2 = (NSNumber *)objc_getAssociatedObject(self, associatedKeyMyname);
NSLog(@"关联姓名之后:%@",associatedName1);
NSLog(@"关联姓名修改:%@",associatedName2);//*> 关联的name没有因为关联对象的值而发成改变!
}
//*> 打印结果:
/*
2016-04-16 22:10:20.778 AssociatedDemo[2648:1100881]
Personal information{
Age = 23;
Gender = Male;
Name = "U5415U6d2aU9633";
}
2016-04-16 22:10:20.779 AssociatedDemo[2648:1100881] 关联姓名之后:吕洪阳
2016-04-16 22:10:20.779 AssociatedDemo[2648:1100881] 关联姓名修改:吕洪阳
*/
2.全屏滑动POP代码##
我的测试代码多多指教