iOS開發(fā)-objc_setAssociatedObject-OC的關(guān)聯(lián)對象

介紹

在OC中要在對象中存放信息,我們需要從對象所屬的類中繼承一個子類,然后改用這個子類的對象。在不想使用子類的情況下,我們可以使用『關(guān)聯(lián)對象』(Associated Object)來處理問題。
給對象關(guān)聯(lián)其他對象,這些對象通過"鍵"來區(qū)分。在存儲對象值的時候,可以設(shè)置"存儲策略"。

typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
    OBJC_ASSOCIATION_ASSIGN = 0,           /**< Specifies a weak reference to the associated object. */
    OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_COPY_NONATOMIC = 3,   /**< Specifies that the associated object is copied. 
                                            *   The association is not made atomically. */
    OBJC_ASSOCIATION_RETAIN = 01401,       /**< Specifies a strong reference to the associated object.
                                            *   The association is made atomically. */
    OBJC_ASSOCIATION_COPY = 01403          /**< Specifies that the associated object is copied.
                                            *   The association is made atomically. */
};

這一點和設(shè)置屬性相同,我們可以類比@propety來理解。
OBJC_ASSOCIATION_ASSIGN ------------------------- assign
OBJC_ASSOCIATION_RETAIN_NONATOMIC ------------ nonatomic, retain
OBJC_ASSOCIATION_COPY_NONATOMIC -------------- nonatomic,copy
OBJC_ASSOCIATION_RETAIN -------------------------- retain
OBJC_ASSOCIATION_COPY ---------------------------- copy

使用

我們可以使用這個特性給系統(tǒng)的類設(shè)置屬性
UIImageView設(shè)置imageURL

#import "objc/runtime.h"
#import "UIImageView+WebCache.h"

static const void *imageURLKey = &imageURLKey;

@implementation UIImageView (WebCache)
- (NSString *)imageURL {
    return objc_getAssociatedObject(self, imageURLKey);
}
- (void)setImageURL:(NSString *)imageURL {
    objc_setAssociatedObject(self, imageURLKey, imageURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end

在使用UIAlertView時,創(chuàng)建視圖與處理按鈕動作分開,很不方便閱讀,我們可以這樣處理。
1.設(shè)置"鍵"值。

static void *AlertViewKey = "AlertViewKey";

2.使用

- (void)askQuestion {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"問題" message:@"你想要做…… ?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
    void (^block)(NSInteger) = ^(NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            [self doCancel];
        } else if (buttonIndex == 1) {
            [self doContinue];
        }
    };
    objc_setAssociatedObject(alertView, AlertViewKey, block, OBJC_ASSOCIATION_COPY);
    [alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    void (^block)(NSInteger) = objc_getAssociatedObject(alertView, AlertViewKey);
    block(buttonIndex);
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容