Object-c Associated Object

oc的关联的作用在我看来就是将两个对象关联起来,用的时候在取出来(我做的项目就是和UITableView里面的一个属性关联起来了)

举个栗子:

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(100, 100, 100, 100);
    [button setTitle:@"关联测试" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonTap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)buttonTap{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@""
                                                     message:@"How (are) you doing" delegate:self cancelButtonTitle:@"Not bad" otherButtonTitles:@"Fine", nil];
    void (^block)(NSInteger) = ^(NSInteger buttonIndex){
        if (buttonIndex == 0) {
            NSLog(@"buttonIndex:0");
        }else{
            NSLog(@"buttonIndex:1");
        }
    };
    objc_setAssociatedObject(alert, key, block, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [alert show];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    void (^block)(NSInteger) = objc_getAssociatedObject(alertView, key);
    block(buttonIndex);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

@end

上面的栗子就是把alert和block关联起来,你关联的什么对象类型,取得就是什么对象类型,然后利用取出来的对象做你想做的事,上面的栗子就是取出block,完了在block里面做你想做的事,并且block在alert后面,使你看代码更容易一些,(在我看来,然并卵),这个栗子也算是我从《Effective Object-c》借鉴来的,真心觉得这个自己不太好,但是对于理解对象关联够用了,OBJC_ASSOCIATION_RETAIN_NONATOMIC这个和(nonatomic,retain)是一样的作用,如下表

OBJC_ASSOCIATION_ASSIGN @property (assign) or @property (unsafe_unretained) Specifies a weak reference to the associated object.
OBJC_ASSOCIATION_RETAIN_NONATOMIC @property (nonatomic, strong) Specifies a strong reference to the associated object, and that the association is not made atomically.
OBJC_ASSOCIATION_COPY_NONATOMIC @property (nonatomic, copy) Specifies that the associated object is copied, and that the association is not made atomically.
OBJC_ASSOCIATION_RETAIN @property (atomic, strong) Specifies a strong reference to the associated object, and that the association is made atomically.
OBJC_ASSOCIATION_COPY @property (atomic, copy) Specifies that the associated object is copied, and that the association is made atomically.

而且,用block还要注意循环引用的问题,这个在这里就不多说了,我个人认为http://kingscocoa.com/tutorials/associated-objects/这个写的不错,是全英文的,不过不难,建议可以看看,理解问题会更上一层楼,这个博客讲解了为什么用关联,举得栗子就是正常写的情况下,记录你要删除的cell的IndexPath,会把这个IndexPath弄成全局变量来记录,完了操作删除,但是要想到一个问题就是我要是在其他地方也操作这个值不就会乱套么,或者我就用一次,用全局变量就太麻烦了,所以索性用关联记录这个值,于是可以模仿我上面的栗子写,不过博主用了三种方法阐述,第一个就是想我上面栗子一样正常写,第二种就是给NSObject加拓展方法,传入对象和关联的值,第三种就是给UIALertView加类方法,把IndexPath设置成属性,重写setter和getter方法,我觉得博主的想法很巧妙,希望借鉴,谢谢

参考链接:http://nshipster.com/associated-objects/

http://kingscocoa.com/tutorials/associated-objects/

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-02 10:10:56

Object-c Associated Object的相关文章

Redis存储Object 和 list<object>

Redis 存储支持的类型没有object ,虽然有支持list,但是只支持List<String> 有两种方法可以实现存储对象和泛型 1.用序列化和反序列化 2.json 序列化工具类,实现序列化和反序列话对象和list集合 package com; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.Object

【JS】☆★之详解[Object HTMLDivElement]和[Object Object]

[JS]☆★之详解[Object HTMLDivElement]和[Object Object] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">

遍历对象属性(for in、Object.keys、Object.getOwnProperty)

js中几种遍历对象的方法,包括for in.Object.keys.Object.getOwnProperty,它们在使用场景方面各有不同. for in 主要用于遍历对象的可枚举属性,包括自有属性.继承自原型的属性 var obj = {"name":"Poly", "career":"it"} Object.defineProperty(obj, "age", {value:"forever

Object obj=new Object()的内存引用

Object obj=new Object(); 一句很简单的代码,但是这里却设计Java栈,Java堆,java方法去三个最重要的内存区域之间的关联. 假设这句代码出现在方法体中. 1.Object obj将反映到Java栈的本地变量表,这是一个本地变量的定义.是一个引用类型. 2.new Object()将会反映在Java堆中.存储了Object类型的所有实例数据值(次内存是不固定大小的,因为谁也无法确定这是对象的大小). 3.程序运行,类型信息已经加载到内存里,这些数据就在Java方法区中

[Javascript] Object.freeze() vs Object.seal()

let person = { firstName: "Zhentian", lastName: "Wan" }; /*Object.freeze() makes object cannot be updated, added or deleted*/ let freezePerson = Object.freeze(person); freezePerson.address="Finland"; // Cannot add property ad

Java基础知识强化26:Object类之Object类的概述

1.Object类 类Object是类层次结构的根类,每个类都使用 Object作为超类.所有对象(包括数组)都实现这个类的方法 每个类直接或者间接继承自Object类 2.Object类无参构造: public  Object() 回想面向对象中为什么说:子类的构造方法默认访问的是父类的无参构造. 答:这是因为所有类的共同父亲Object只有一个无参构造. 来自为知笔记(Wiz)

微信小程序把玩(三十一)wx.uploadFile(object), wx.downloadFile(object) API

原文:微信小程序把玩(三十一)wx.uploadFile(object), wx.downloadFile(object) API 反正我是没有测通这两个API!!!!不知道用的方式不对还是其他的!!!先记录下回头再说... 主要方法: wx.uploadFile(OBJECT)上传 wx.downloadFile(OBJECT)下载 wxml <button type="primary" bindtap="listenerButtonDownLoadFile"

jq 插件 的两个相关的函数 jQuery.fn.extend(object); jQuery.extend(object);

jQuery为开发插件提拱了两个方法,分别是:  http://www.cnblogs.com/wyjgreat/archive/2011/07/19/2110754.html JavaScript代码 jQuery.fn.extend(object); jQuery.extend(object); jQuery.extend(object); 为扩展jQuery类本身.为类添加新的方法. jQuery.fn.extend(object);给jQuery对象添加方法. fn 是什么东西呢.查看j

JS Object.getOwnPropertyDescriptor()和Object.defineProperty()

ECMAScript 5 对对象属性进行了重新定义.除了原有的 property:value外,还增加了一些用于 标识该属性是否可写,可枚举,可配置的特性.为此引入了两个新方法:Object.getOwnPropertyDescriptor()和Object.defineProperty(). <script> var person ={ name:"Hai" }; //定义一个新对象 var personName = Object.getOwnPropertyDescri

自学Python-列表list(object) 元组tuple(object) 方法

Python List方法总结 class list(object): """ list() -> new empty list list(iterable) -> new list initialized from iterable's items """ def append(self, p_object): # real signature unknown; restored from __doc__ ""&