ios - WatchKit SDK 未从 NSUserDefaults 检索数据

标签 ios objective-c xcode xcode6 watchkit

我想为 Apple Watch 做一个测试应用,你可以在手机上设置一些字符串,然后它就会显示在 Apple Watch 上。我决定使用 NSUserDefaults 类来存储这些数据。

在我的 iPhone View Controller 中,我有一个方法可以将输入存储到本地存储中:

- (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"];
}

在我的 watch 界面 Controller 中,我有一个方法可以检索数据并显示它:

- (IBAction)showText2 {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults synchronize];

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

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

最佳答案

+standardUserDefaults 返回一个 NSUserDefaults 对象,它只保存当前进程的信息。

如果你想创建一个 NSUserDefaults 对象来在你的 iOS 应用程序和它的一个扩展之间共享数据,那么你需要 set up an app group container并将其作为共享信息的基础。

来自链接文档:

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"];

注意:在 watch OS2 中,您不能再使用共享组容器。

关于ios - WatchKit SDK 未从 NSUserDefaults 检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27007288/

相关文章:

ios - 如何在 TableView Cell 上使用 iOSCharts (https ://github. com/danielgindi/Charts)?

ios - 如何从 xcode 卸载 swiftlint,或关闭它的警告

ios - -ObjC 链接器标志导致重复符号错误

ios - 在运行连接到IPv6网络的iOS 10.0.2时,苹果商店上的二进制拒绝

ios - Objective-C - 表达式不是整数常量表达式

ios - 来自后台的远程通知

iphone - 动态地全局将(null)替换为'0'

ios - 学习 Swift 并尝试在标签中创建字符串循环

ios - 特定日期格式的日期格式化程序

Objective-C:如何在 switch 语句完成后返回到应用程序的开头