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're seeing was required in earlier versions of Objective-C,
but isn'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'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's instance
variables.</p>
<p>When properties were introduced, synthesized properties had to be
"backed" by an instance variable in the class'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're creating at runtime (only before you'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're seeing is redundant and should not
be considered a "best practice".</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]