菜鸟教程小白 发表于 2022-12-11 18:03:16

ios - UserDefault 总是返回 nil


                                            <p><p><code>UserDefaults</code> 在我的应用程序中不起作用。请在 <code>AppDelegate</code> 文件下找到以下代码。</p>

<pre><code>let sharingData = UserDefaults.init(suiteName: &#34;group.macuser79.xxx&#34;);
sharingData?.set(&#34;vincenzo&#34;, forKey:&#34;username&#34;);
sharingData?.synchronize();
</code></pre>

<p>在要 Watch 的应用程序的 InterfaceController 中,为了能够检索值所以我这样做了:</p>

<pre><code>override func awake(withContext context: Any?) {
let sharingData = UserDefaults.init(suiteName: &#34;group.macuser79.xxx&#34;);

let username = sharingData?.object(forKey: &#34;username&#34;);
    print(&#34;Value username \(username)&#34;);
}
</code></pre>

<p>请告诉我,我做错了什么!</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>在 <code>Swift3</code> <code>UserDefaults</code> 中获取存储值变得更加智能。在下面的行中,您正在存储 <code>String</code> 值而不指定它!:</p>

<pre><code>sharingData?.set(&#34;vincenzo&#34;, forKey:&#34;username&#34;);
</code></pre>

<p>所以,为了得到它,你需要像下面这样写:</p>

<pre><code>let username = sharingData?.string(forKey: &#34;username&#34;);
    print(&#34;Value username \(username)&#34;);
}
</code></pre>

<p>这是根据您的商店获取值(value)的更好的上下文。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - UserDefault 总是返回 nil,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/40589475/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/40589475/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - UserDefault 总是返回 nil