使用objc_setAssociatedObject和弱引用 [英] Using objc_setAssociatedObject with weak references

查看:214
本文介绍了使用objc_setAssociatedObject和弱引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道OBJC_ASSOCIATION_ASSIGN存在,但是如果取消分配目标对象,是否会将引用归零?还是就像过去需要删除该参考文献的旧时代一样,否则我们以后可能会有访问不当的风险?

I know that OBJC_ASSOCIATION_ASSIGN exists, but does it zero the reference if the target object is dealloced? Or is it like the old days where that reference needs to get nil-ed or we risk a bad access later on?

推荐答案

尝试后,答案是否定的.

After trying it out, the answer is NO.

我在iOS 6模拟器下运行了以下代码,但是它可能与运行时的先前迭代具有相同的行为:

I ran the following code under the iOS 6 Simulator, but it would probably have the same behavior with previous iterations of the runtime:

NSObject *test1 = [NSObject new];

NSObject __weak *test2 = test1;

objc_setAssociatedObject(self, "test", test1, OBJC_ASSOCIATION_ASSIGN);

test1 = nil;

id test3 = objc_getAssociatedObject(self, "test");

最后,test1和test2为零,而test3是先前存储在test1中的指针.使用test3将导致尝试访问已经取消分配的对象.

In the end, test1 and test2 are nil, and test3 is the pointer previously stored into test1. Using test3 would result in trying to access an object that had already been dealloced.

这篇关于使用objc_setAssociatedObject和弱引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆