WatchKit SDK无法从NSUserDefaults检索数据 [英] WatchKit SDK not retrieving data from NSUserDefaults

查看:139
本文介绍了WatchKit SDK无法从NSUserDefaults检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为Apple手表制作测试应用程序,您可以在手机上设置一些字符串,然后它将显示在Apple Watch上。我决定使用NSUserDefaults类来存储这些数据。

I wanted to make a test app for the Apple watch in which you can set some String on your phone, and then it will be displayed on the Apple Watch. I decided to use NSUserDefaults class to store this data.

在我的iPhone视图控制器中,我有一个方法可以将输入和存储到本地存储中:

In my view controller for the iPhone I have a method which takes the input and stores into local storage:

- (IBAction)saveInfo:(id)sender {

    NSString *userInput = [myTextField text];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject:userInput forKey:@"savedUserInput"];

    [defaults synchronize];

    self.myLabel.text = [defaults stringForKey:@"savedUserInput"];
}

在我的监视界面控制器中,我有一个检索数据和显示的方法它:

And in my watch interface controller I have a method that retrieves the data and displays it:

- (IBAction)showText2 {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults synchronize];

    self.myLabel2.text = [defaults stringForKey:@"savedUserInput"];
}

除了某些原因我尝试检索的数据显示为null,并且标签没有更新。

Except for some reason the data I am trying to retrieve is shown as null, and the label is not being updated.

推荐答案

+ standardUserDefaults 返回 NSUserDefaults 仅保存当前进程信息的对象。

+standardUserDefaults returns an NSUserDefaults object that only saves information for the current process.

如果要创建 NSUserDefaults 在iOS应用程序和其中一个扩展程序之间共享数据的对象,然后您需要设置应用程序组容器并将其用作共享信息的基础。

If you want to create an NSUserDefaults object that shares data between your iOS app and one of its extensions, then you'll need to set up an app group container and use that as the basis for sharing information.

来自链接文档:


启用应用程序组后,应用程序扩展及其包含应用程序都可以使用NSUserDefaults API共享对用户首选项的访问权限。要启用此共享,请使用initWithSuiteName:方法实例化新的NSUserDefaults对象,并传入共享组的标识符。例如,共享扩展程序可能会使用以下代码更新用户最近使用的共享帐户:

After you enable app groups, an app extension and its containing app can both use the NSUserDefaults API to share access to user preferences. To enable this sharing, use the initWithSuiteName: method to instantiate a new NSUserDefaults object, passing in the identifier of the shared group. For example, a Share extension might update the user’s most recently used sharing account, using code like this:

// Create and share access to an NSUserDefaults object.
NSUserDefaults *mySharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.example.domain.MyShareExtension"];

// Use the shared user defaults object to update the user's account.
[mySharedDefaults setObject:theAccountName forKey:@"lastAccountName"];


注意: 使用手表OS2,您无法再使用共享组容器。

NOTE: With watch OS2 you can no longer use shared group containers.

这篇关于WatchKit SDK无法从NSUserDefaults检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆