运行时添加BOOL属性,及懒加载BOOL属性。

2017-07-20  本文已影响0人  Linco_Yang

关于类目(分类)能不能或者说应不应该添加属性,本文不做讨论。只是介绍利如何用运行时为类添加属性。

/** 
 * 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)
    OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0);

/** 
 * 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)
    OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0);

/** 
 * Removes all associations for a given object.
 * 
 * @param object An object that maintains associated objects.
 * 
 * @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.
 * 
 * @see objc_setAssociatedObject
 * @see objc_getAssociatedObject
 */
OBJC_EXPORT void objc_removeAssociatedObjects(id object)
    OBJC_AVAILABLE(10.6, 3.1, 9.0, 1.0);

以上三个为<objc/runtime.h>里提供的在运行时处理属性的方法。
·第一个是添加关联策略
·第二个是获取关联策略
·第三个是移除所有关联策略(慎用!!!)
·如果需要移除某个关联策略,那么可以使用第一个方法,传入参数为nil即可。

网上已经有大量的相关的方法。但是大多是对象类型,缺少基本数据类型的添加。
下面就是以BOOL类型为例子,进行相关的处理。

const void *theKey = @"theKey";
- (void)setYourProperty:(BOOL)yourPropertyName {
    objc_setAssociatedObject(self, theKey, @(isXXX), OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)yourProperty {
    return [objc_getAssociatedObject(self, theKey) boolValue];
}

上面是利用运行时方法为某个类添加一个BOOL类型的属性。下面介绍常规的BOOL属性赋初值的方法。利用懒加载给一个BOOL属性赋一个初值。(ARC环境)

初值为NO的情况:

- (BOOL)isXXX {
    if (!_isXXX) {
        _isXXX = NO;
    }
    return _isXXX;
}

初值为YES的情况:
因为布尔属性在没有初值的情况下值并不明确,类似于NO的情况,那么可以利用dispatch_once_t函数进行处理。虽然官方API里面解释的是"Use lazily initialized globals instead",但是布尔类型基本数据类型,使用的是assign来修饰。不会产生内存问题。

- (BOOL)isXXX {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _isXXX = YES;
    });
    return _isXXX;
}
上一篇下一篇

猜你喜欢

热点阅读