菜鸟教程小白 发表于 2022-12-12 19:10:58

ios - 如何在运行时确定只读属性是否弱?


                                            <p><p>我有一个声明两个属性的类。</p>

<pre><code>@property (nonatomic, readonly, weak) id first;
@property (nonatomic, weak) id second;
</code></pre>

<p>我在运行时使用以下代码检查属性的属性:</p>

<pre><code>unsigned int propertyCount;
objc_property_t *properties = class_copyPropertyList(class, &amp;propertyCount);
for (int propertyIndex = 0; propertyIndex &lt; propertyCount; propertyIndex++) {
    objc_property_t property = properties;
    const char *rawName = property_getName(property);
    NSString *propertyName = ];
    BOOL isWeak = ;
    char const *attributes = property_getAttributes(property);
    NSString *attributesString = ];
    NSArray *attributesArray = ;
    BOOL weak = ;
    NSLog(@&#34;attributes of property are %@.Weak? %d&#34;, attributesString, weak);
}
</code></pre>

<p>不幸的是,我得到了这些结果:</p>

<pre><code>attributes of property are T@,R,N,V_first.Weak? 0
attributes of property are T@,W,N,V_second.Weak? 1
</code></pre>

<p>从 <a href="https://developer.apple.com/library/mac/documentation/cocoa/conceptual/objcruntimeguide/articles/ocrtpropertyintrospection.html" rel="noreferrer noopener nofollow">https://developer.apple.com/library/mac/documentation/cocoa/conceptual/objcruntimeguide/articles/ocrtpropertyintrospection.html</a> 的文档中可以清楚地看出第一个属性也应该有一个“W”,但它没有。有谁知道如何检测这个属性实际上很弱?</p>

<p>请注意,将它声明为弱确实很重要,编译器会关心并适本地对待它。</p>

<p>这似乎是一个错误,但我仍然需要一个真正有效的方法。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>将其设置为只读仅意味着您没有创建 setter 方法。所以将其设置为弱,是违反直觉的。除了更改合成 ivar 的生命周期限定符之外,强/弱修饰符对只读属性没有任何影响</p>

<p>我会在 .h 中将其设置为只读,然后如果您希望它成为 .m 文件中的弱变量,则有 </p>

<pre><code>@property (nonatomic, weak) id first
</code></pre>

<p>这样它在外部是只读的,但如果这是你想要的,那么它在内部是弱的。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何在运行时确定只读属性是否弱?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/21941418/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/21941418/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何在运行时确定只读属性是否弱?