什么是關(guān)聯(lián)對象
關(guān)聯(lián)對象是指某個OC對象通過一個唯一的key連接到一個類的實例上。
舉個例子:xiaoming是Person類的一個實例,他的dog(一個OC對象)通過一根繩子(key)被他牽著散步,這可以說xiaoming和dog是關(guān)聯(lián)起來的,當然xiaoming可以牽著多個dog。
怎樣關(guān)聯(lián)對象
runtime提供給我們的方法:
//關(guān)聯(lián)對象
void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
//獲取關(guān)聯(lián)的對象
id objc_getAssociatedObject(id object, const void *key)
//移除關(guān)聯(lián)的對象
void objc_removeAssociatedObjects(id object)
變量說明:
id object:被關(guān)聯(lián)的對象(如xiaoming)
const void *key:關(guān)聯(lián)的key,要求唯一
id value:關(guān)聯(lián)的對象(如dog)
objc_AssociationPolicy policy:內(nèi)存管理的策略
objc_AssociationPolicy policy的enum值有:
OBJC_ASSOCIATION_ASSIGN = 0,
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
OBJC_ASSOCIATION_RETAIN = 01401,
OBJC_ASSOCIATION_COPY = 01403
當對象被釋放時,會根據(jù)這個策略來決定是否釋放關(guān)聯(lián)的對象,當策略是RETAIN/COPY時,會釋放(release)關(guān)聯(lián)的對象,當是ASSIGN,將不會釋放。
值得注意的是,我們不需要主動調(diào)用removeAssociated來接觸關(guān)聯(lián)的對象,如果需要解除指定的對象,可以使用setAssociatedObject置nil來實現(xiàn)。
關(guān)聯(lián)對象的應用
1、添加公共屬性
這是最常用的一個模式,通常我們會在類聲明里面添加屬性,但是出于某些需求(如前言描述的情況),我們需要在分類里添加一個或多個屬性的話,編譯器就會報錯,這個問題的解決方案就是使用runtime的關(guān)聯(lián)對象。
應用舉例:
我們需要自定義一個tabbar,并暴露公共的屬性和方法。(讀者們可以思考下使用繼承和分類實現(xiàn)的優(yōu)點和不足之處)
@interface UITabBarController (Custom)
@property (nonatomic, strong) SUCustomTabbar * customTabbar;
@end
#import "UITabBarController+Custom.h"
#import <objc/runtime.h>
@implementation UITabBarController (Custom)
- (void)setCustomTabbar:(UIView *)customTabbar {
//這里使用方法的指針地址作為唯一的key
objc_setAssociatedObject(self, @selector(customTabbar), customTabbar, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIView *)customTabbar {
return objc_getAssociatedObject(self, @selector(customTabbar));
}
//其他方法...
@end
這樣,我們就可以像原生的tabbar一樣使用自定義的tabbar:
[self.tabBarController.customTabbar doSomgthig];
例如在iOS中我們都是用過UIAlert類,當用戶要處理點擊事件的時候,需要通過委托協(xié)議來實現(xiàn)。這時候就需要把視圖和事先動作的代碼分開。例如:
-(void)userAlert {
UIAlert *alert = [[UIAlert alloc] initWithTitle:@"Alert"
message:@"do you want to close?"
delegate: self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK",nil];
[alert show];
}
#param -mark UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger:)buttonIndex{
if(buttonIndex == 0){
//do action
} else {
//do action
}
}
通常都是這么做,但是如果代碼中使用多個UIAlerView的時候,還需要通過在回調(diào)中判斷alertView的類型,然后再去處理響應的邏輯。要是能夠是創(chuàng)建視圖的時候,就把每個按鈕響應的邏輯寫好,那就簡單多了。于是可以:
_alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"This is deprecated?"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Ok", nil];
void (^block)(NSInteger) = ^(NSInteger buttonIndex){
if (buttonIndex == 0) {
[self doCancel];
} else {
[self doOk];
}
};
objc_setAssociatedObject(self.alertView, MyAlertViewKey, block, OBJC_ASSOCIATION_COPY);
#pragma -mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
void (^block)(NSInteger) = objc_getAssociatedObject(alertView, MyAlertViewKey);
block(buttonIndex);
}
2、添加私有成員變量
有時候,需要在分類中添加不想暴露在公共聲明的成員變量。
應用舉例:給按鈕添加點擊時間的回調(diào)
@interface UIButton (Callback)
- (instancetype)initWithFrame:(CGRect)frame callback:(void (^)(UIButton *))callbackBlock;
@end
@interface UIButton ()
@property (nonatomic, copy) void (^callbackBlock)(UIButton * button);
@end
@implementation UIButton (Callback)
- (void (^)(UIButton *))callbackBlock {
return objc_getAssociatedObject(self, @selector(callbackBlock));
}
- (void)setCallbackBlock:(void (^)(UIButton *))callbackBlock {
objc_setAssociatedObject(self, @selector(callbackBlock), callbackBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (instancetype)initWithFrame:(CGRect)frame callback:(void (^)(UIButton *))callbackBlock {
if (self = [super initWithFrame:frame]) {
self.callbackBlock = callbackBlock;
[self addTarget:self action:@selector(didClickAction:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (void)didClickAction:(UIButton *)button {
self.callbackBlock(button);
}
@end
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。