ios - if(objc_getAssociatedObject(self, &Key)) 为 nil 对象返回 true
<p><p>如何测试 <code>objc_getAssociatedObject</code> 是否为 <code>nil</code>?下面说元素不是 <code>nil</code> 但关联的对象之前从未设置过也没有被访问过。</p>
<pre><code>static char orderedElementKey = 11;
if (objc_getAssociatedObject(self, &orderedElementKey) != nil)
{
NSLog(@"element is not nil");
return objc_getAssociatedObject(self, &orderedElementKey);
}
NSLog(@"elelement was nil !");
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><pre><code>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 !");
}
</code></pre>
<p>打印“元素零!”在删除 <code>objc_setAssociatedObject()</code> 上的注释时会打印“Element: value”。你的代码有什么不同?</p></p>
<p style="font-size: 20px;">关于ios - if(objc_getAssociatedObject(self, &Key)) 为 nil 对象返回 true,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/20002279/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/20002279/
</a>
</p>
页:
[1]