OGeek|极客世界-中国程序员成长平台

标题: ios - if(objc_getAssociatedObject(self, &Key)) 为 nil 对象返回 true [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 16:24
标题: ios - if(objc_getAssociatedObject(self, &Key)) 为 nil 对象返回 true

如何测试 objc_getAssociatedObject 是否为 nil?下面说元素不是 nil 但关联的对象之前从未设置过也没有被访问过。

static char orderedElementKey = 11;

if (objc_getAssociatedObject(self, &orderedElementKey) != nil)
{
    NSLog(@"element is not nil");
    return objc_getAssociatedObject(self, &orderedElementKey);
}
NSLog(@"elelement was nil !");



Best Answer-推荐答案


static char orderedElementKey = 11;
//objc_setAssociatedObject(self, &orderedElementKey, @"value", OBJC_ASSOCIATION_RETAIN);

if (objc_getAssociatedObject(self, &orderedElementKey) != nil)
{
    NSLog(@"Element: %@", objc_getAssociatedObject(self, &orderedElementKey));
}
else
{
    NSLog(@"element nil !");
}

打印“元素零!”在删除 objc_setAssociatedObject() 上的注释时会打印“Element: value”。你的代码有什么不同?

关于ios - if(objc_getAssociatedObject(self, &Key)) 为 nil 对象返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20002279/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4