(十) [OC高效系列]在既有類中使用關(guān)聯(lián)對象存放自定義數(shù)據(jù)

1.關(guān)聯(lián)是什么

是指動態(tài)創(chuàng)建一個指針從一個對象指向另外一個對象,并且遵循相應(yīng)的“內(nèi)存管理語義”,相當(dāng)于動態(tài)添加一個屬性

2.關(guān)聯(lián)的類型與等效的property屬性

關(guān)聯(lián)類型 等效的@property屬性
OBJC_ASSOCIATION_ASSIGN assign
OBJC_ASSOCIATION_RETAIN_NONATOMIC nonatomic, retain
OBJC_ASSOCIATION_COPY_NONATOMIC nonatomic, copy
OBJC_ASSOCIATION_RETAIN retain

3.關(guān)聯(lián)的相關(guān)api

設(shè)置關(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)

4.以靜態(tài)全局變量作為key

  • 設(shè)置關(guān)聯(lián)對象的key和NSDictionary中的key不一樣。其在術(shù)語上屬于“不透明的指針”。
  • NSDictionary中,兩個key如果isEqual方法返回YES,則認(rèn)為兩個key相同。
  • 而這里要完全相同。

5.使用關(guān)聯(lián)對象好處在哪里?如果要擴(kuò)充屬性,創(chuàng)建一個子類不就行了?

使用繼承的方式擴(kuò)充屬性,則代碼具有侵入性。OC中是單繼承模式,繼承了A就無法繼承B,還有另外的C。所以某種特定的情況下,無法使用繼承。

更多的是使用分類+關(guān)聯(lián)的方式來擴(kuò)充一個已經(jīng)存在的類。這樣代碼沒有侵入性,使用起來更加簡單簡便。

6.UIImageView+WebCache中使用的關(guān)聯(lián)

UIImageView+WebCache中每次設(shè)置新的圖片的時候都會將當(dāng)前imageView正在加載的進(jìn)程給取消了。而這些進(jìn)程對象就是通過關(guān)聯(lián)的方式動態(tài)關(guān)聯(lián)到imageView上。

//UIImageView+WebCache.m
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
    [self sd_cancelCurrentImageLoad];
    ...
    if (url) {
        __weak UIImageView *wself = self;
        id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
           ...
        }];
        [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"];
    } else {
       ...
    }
}

- (void)sd_cancelCurrentImageLoad {
    [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"];
}

//UIView+WebCacheOperation.m
- (NSMutableDictionary *)operationDictionary {
    NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
    if (operations) {
        return operations;
    }
    operations = [NSMutableDictionary dictionary];
    objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    return operations;
}

- (void)sd_setImageLoadOperation:(id)operation forKey:(NSString *)key {
    [self sd_cancelImageLoadOperationWithKey:key];
    NSMutableDictionary *operationDictionary = [self operationDictionary];
    [operationDictionary setObject:operation forKey:key];
}

7.使用關(guān)聯(lián)還可以使 因為delegate形式而變得分散的代碼 通過block的形式 集中到一起。這樣可讀性更強(qiáng),代碼更簡潔。

以UIActionSheet為例。

先來一個不使用關(guān)聯(lián)時的代碼。

@interface ViewController () <UIActionSheetDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
}

- (IBAction)didClickBtn:(UIButton *)btn{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Hellow World" delegate:self cancelButtonTitle:@"不hellow" destructiveButtonTitle:@"hellow1" otherButtonTitles:@"hellow2",nil];
    [sheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
   NSLog(@"點擊了 %ld",buttonIndex);
}

@end

這樣點擊actionsheet后的邏輯與創(chuàng)建時候的代碼是分開的,當(dāng)代碼一多的情況下,這個代理方法和其他的代理方法放在一起,可讀性比較差。而且每次創(chuàng)建一個UIActionSheet都需要:

  • 設(shè)置代理
  • 添加代理protocol
  • 實現(xiàn)相關(guān)代理方法

--

使用關(guān)聯(lián)我們可以將ActionSheet的相關(guān)邏輯獨立成一個Tool,代碼如下

//.m
static char tool;
static char sheet;

@interface YXActionSheetTool () <UIActionSheetDelegate>
@property (nonatomic,copy) void(^callback)(NSInteger clickIndex);
@property (nonatomic,weak) UIViewController *controller;
@end

@implementation YXActionSheetTool
+ (void)showWithController:(UIViewController *)controller title:(NSString *)title cancleTitle:(NSString *)cancleTitle destructiveTitle:(NSString *)destructiveTitle otherTitles:(NSArray *)otherTitles callback:(void(^)(NSInteger clickIndex))callback {
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:title delegate:nil cancelButtonTitle:cancleTitle destructiveButtonTitle:destructiveTitle otherButtonTitles:nil];
    for (NSString *otherTitle in otherTitles) {
        [sheet addButtonWithTitle:otherTitle];
    }
    YXActionSheetTool *actionSheetTool = [[YXActionSheetTool alloc] init];
    objc_setAssociatedObject(controller,&tool,actionSheetTool,OBJC_ASSOCIATION_RETAIN_NONATOMIC);//防止tool被釋放
    objc_setAssociatedObject(actionSheetTool,&sheet,sheet,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    actionSheetTool.callback=callback;
    actionSheetTool.controller =controller;
    sheet.delegate=actionSheetTool;
    [sheet showInView:controller.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    objc_setAssociatedObject(self,&sheet,nil,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self.controller,&tool,nil,OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    if(self.callback)
     self.callback(buttonIndex);
    
}

@end

調(diào)用代碼如下


@interface ViewController () <UIActionSheetDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
}

- (IBAction)didClickBtn:(UIButton *)btn{ 
    [YXActionSheetTool showWithController:self title:@"Hellow World" cancleTitle:@"不hellow" destructiveTitle:@"hellow1" otherTitles:@[@"hellow2"] callback:^(NSInteger clickIndex) {
        NSLog(@"點擊了 %ld",clickIndex);
    }];
}

@end

這樣就使ui代碼和邏輯代碼在一起,方便閱讀。

最后編輯于
?著作權(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)容