菜鸟教程小白 发表于 2022-12-13 02:32:47

ios - 需要有关 UIViewController 的帮助


                                            <p><p>在多个 UIViewController 一起工作的应用程序中,</p>

<p><code>firstViewController</code> 添加到根目录。到这里为止很好,现在我想转到 <code>secondViewController</code> 我不想使用 <code>UINavigationController</code> 或 <code>UITabBarController</code>。我已经阅读了<a href="http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/Introduction/Introduction.html" rel="noreferrer noopener nofollow">View Controller Programming Guide</a>但它没有使用 <code>UINavigationController、UITabBarController 和 Storyboard </code>来指定。</p>

<p>当用户想要从 <code>secondViewController</code> 移动到 <code>firstViewController</code> 时,<code>secondViewController</code> 将如何被销毁?</p>

<p>Apple Doc 也没有指定 UIViewController 是如何释放或销毁的?它只告诉<code>UIViewController</code>里面的生命周期。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>如果您担心 <strong>UIViewController</strong> 是如何被释放或销毁的,那么这里有一个适合您的场景:-</p>

<p>这是一个 <strong>FirstViewController 中的按钮点击方法</strong>,它呈现 <strong>SecondViewController</strong>(使用 pushViewController、presentModalViewController 等)</p>

<p><strong>在 FirstViewController.m 文件中</strong></p>

<pre><code>- (IBAction)btnTapped {

    SecondViewController * secondView = [initWithNibName:@&#34;SecondViewController&#34; bundle:nil];
    NSLog(@&#34;Before Present Retain Count:%d&#34;,);
    ;
    NSLog(@&#34;After Present Retain Count:%d&#34;,);
    ;//not releasing here is memory leak(Use build and analyze)
}
</code></pre>

<p><strong>现在在 SecondViewController.m 文件中</strong></p>

<pre><code>- (void)viewDidLoad {
    ;
    NSLog(@&#34;View Load Retain Count %d&#34;,);
}

- (void)dealloc {
    ;
    NSLog(@&#34;View Dealloc Retain Count %d&#34;,);
}
</code></pre>

<p><strong>运行代码后:</strong></p>

<blockquote>
<p>Before Push Retain Count:1<br/>
   View Load Retain Count 3<br/>
   After Push Retain Count:4<br/>
   View Dealloc Retain Count 1</p>
</blockquote>

<p>如果你正在分配和初始化一个 ViewController,你是它生命周期的所有者,你必须在 <strong>push 或 modalPresent</strong> 之后释放它。
在上面的输出中,在 <strong>alloc init</strong> 时 SecondViewController 的保留计数为一,,,, 令人惊讶的是,但逻辑上它的保留计数即使在被释放后仍为一(请参阅 dealloc 方法),因此需要一个在 FirstViewController 中释放以完全销毁它。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 需要有关 UIViewController 的帮助,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/16333731/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/16333731/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 需要有关 UIViewController 的帮助