iOS中關聯對象的簡單使用objc_setAssociatedObject


 

首先看一下此方法接收的參數

objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)

被關聯的對象,下面舉的例子中關聯到了UIAlertView

  • 要關聯的對象的鍵值,一般設置成靜態的,用於獲取關聯對象的值
  • 要關聯的對象的值,從接口中可以看到接收的id類型,所以能關聯任何對象
  • 關聯時采用的協議,有assign,retain,copy等協議,具體可以參考官方文檔

下面就以UIAlertView為例子簡單介紹一下使用方法

使用場景:在UITableView中點擊某一個cell,這時候彈出一個UIAlertView,然后在UIAlertView消失的時候獲取此cell的信息,我們就獲取cell的indexPath

第一步:

#import <objc/runtime.h>
static char kUITableViewIndexKey;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
......
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                message:@"這里是xx樓"
                                               delegate:self
                                      cancelButtonTitle:@"好的"
                                      otherButtonTitles:nil];
//然后這里設定關聯,此處把indexPath關聯到alert上
objc_setAssociatedObject(alert, &kUITableViewIndexKey, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[alert show];

}

第二步:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
    NSIndexPath *indexPath = objc_getAssociatedObject(alertView, &kUITableViewIndexKey);
    NSLog(@"%@", indexPath);
    }
}   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM