应用程序及其扩展程序之间的数据共享通过公共(public)应用程序组发生。我可以使用共享应用程序组容器作为持久数据/文件存储。如何创建/使用共享应用程序组容器作为包含应用程序及其扩展之间的缓存存储?这可能吗?
最佳答案
是的,您走在正确的轨道上。这是可能的。
在主应用目标和 WatchKit 扩展目标的 Capabilities
选项卡中,添加一个应用组,例如,名称为 group.myWatchDefaults
。
然后您可以像这样访问默认值:
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.myWatchDefaults"];
添加数据:
[defaults setObject:[NSNumber numberWithBool:true] forKey:@"myBoolVariable"];
检索数据:
bool watchAppOpenedBefore = [[defaults objectForKey:@"myBoolVariable"] boolValue];
确保在更改默认值后使用同步
:
[defaults synchronize];
有时,在使用 Xcode 的模拟器时,使用应用程序组在 Watch 应用程序及其父应用程序之间同步 NSUserDefaults 不起作用。但是,它适用于实际设备(iPhone 和 Apple Watch)。因此,这似乎是模拟器中的错误。
关于ios - 如何创建/使用共享应用程序组容器作为包含应用程序及其在 ios 中的扩展之间的缓存存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30154834/