關(guān)于類目(分類)能不能或者說應(yīng)不應(yīng)該添加屬性揍愁,本文不做討論呐萨。只是介紹利如何用運(yùn)行時(shí)為類添加屬性。
/**
* 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);
以上三個(gè)為<objc/runtime.h>里提供的在運(yùn)行時(shí)處理屬性的方法吗垮。
·第一個(gè)是添加關(guān)聯(lián)策略
·第二個(gè)是獲取關(guān)聯(lián)策略
·第三個(gè)是移除所有關(guān)聯(lián)策略(慎用6饴稹!K傅恰)
·如果需要移除某個(gè)關(guān)聯(lián)策略怯屉,那么可以使用第一個(gè)方法蔚舀,傳入?yún)?shù)為nil即可。
網(wǎng)上已經(jīng)有大量的相關(guān)的方法锨络。但是大多是對(duì)象類型赌躺,缺少基本數(shù)據(jù)類型的添加。
下面就是以BOOL類型為例子羡儿,進(jìn)行相關(guān)的處理礼患。
const void *theKey = @"theKey";
- (void)setYourProperty:(BOOL)yourPropertyName {
objc_setAssociatedObject(self, theKey, @(isXXX), OBJC_ASSOCIATION_ASSIGN);
}
- (BOOL)yourProperty {
return [objc_getAssociatedObject(self, theKey) boolValue];
}
上面是利用運(yùn)行時(shí)方法為某個(gè)類添加一個(gè)BOOL類型的屬性。下面介紹常規(guī)的BOOL屬性賦初值的方法掠归。利用懶加載給一個(gè)BOOL屬性賦一個(gè)初值缅叠。(ARC環(huán)境)
初值為NO的情況:
- (BOOL)isXXX {
if (!_isXXX) {
_isXXX = NO;
}
return _isXXX;
}
初值為YES的情況:
因?yàn)椴紶枌傩栽跊]有初值的情況下值并不明確,類似于NO的情況虏冻,那么可以利用dispatch_once_t
函數(shù)進(jìn)行處理肤粱。雖然官方API里面解釋的是"Use lazily initialized globals instead",但是布爾類型基本數(shù)據(jù)類型厨相,使用的是assign來修飾领曼。不會(huì)產(chǎn)生內(nèi)存問題。
- (BOOL)isXXX {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_isXXX = YES;
});
return _isXXX;
}