问题描述
我想为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.
来自链接文档:
// 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检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!