菜鸟教程小白 发表于 2022-12-11 17:20:44

ios - 为什么我必须在头文件中定义两次变量?


                                            <p><p>为什么我必须在头文件中定义两次变量?这些变量之间有什么区别?</p>

<p>第一个定义在这里:</p>

<pre><code>@interface MyController: UIViewController
{
    NSInteger selectedIndex;
}
</code></pre>

<p>第二个定义在这里:</p>

<pre><code>@property (nonatomic) NSInteger selectedIndex;
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><blockquote>
<p>What you&#39;re seeing was required in earlier versions of Objective-C,
but isn&#39;t any more.</p>

<p>In the first versions of Objective-C used by NeXT up until the new
runtime was introduced (with Objective-C 2.0 on Mac OS X), all
instance variables had to be declared as part of the class&#39;s structure
in its <code>@interface</code>. The reason was that if you subclassed a class,
the compiler needed to know the instance variable layout of the class
so it could see at what offset to put the subclass&#39;s instance
variables.</p>

<p>When properties were introduced, synthesized properties had to be
&#34;backed&#34; by an instance variable in the class&#39;s structure. Therefore
you had to declare both an instance variable and the property.</p>

<p>All of the above is no longer true. Newer Objective-C is less fragile
in the way it looks up instance variable offsets, which has meant a
few changes:</p>

<ul>
<li>not all instance variables need to be in the <code>@interface</code>. They can now be defined in the <code>@implementation</code>: though not in categories due
to the possibilities of clashing and other issues.</li>
<li>instance variables for synthesized properties can be inferred and created based on the property definition.</li>
<li>you can programmatically add instance variables to classes you&#39;re creating at runtime (only before you&#39;ve registered the class as
available to the system).</li>
</ul>

<p>So, to reiterate, you only needed to declare both the instance
variable and a synthesized property in older versions of the
Objective-C language. What you&#39;re seeing is redundant and should not
be considered a &#34;best practice&#34;.</p>
</blockquote>

<p><sup> <a href="https://stackoverflow.com/a/11034032/916299" rel="noreferrer noopener nofollow"></a> </sup></p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 为什么我必须在头文件中定义两次变量?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/39116583/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/39116583/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 为什么我必须在头文件中定义两次变量?