介紹
在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);
}