Watch OS 2 - 如何在 Watch 上为完全原生的应用程序存储数据? [英] Watch OS 2 - How store data on Watch for fully native app?

查看:18
本文介绍了Watch OS 2 - 如何在 Watch 上为完全原生的应用程序存储数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 WatchKit Extension - Watch 端存储大约 5 个变量.该应用程序将是完全原生的,无需向 iPhone 传递任何信息.如果手表重新启动,我需要数据保持不变.应用程序当前会在重新启动时重置为默认变量状态.我不确定要使用什么.我在网上找到了有关使用手表钥匙串存储键值数据对(用户名/密码)的信息,但我认为我不应该在这里使用它.感谢一些帮助.

I need to store about 5 variables on the WatchKit Extension - Watch side Only. The app is going to be completely native, without passing any info to the iPhone. I need the data to persist if the watch is re-booted. The app currently resets to the default variable states upon reboot. I'm not sure what to use. I found information online about using the watch keychain for storing key-value data pairs (username/password), but I don't think that's what I should use here. Appreciate some help.

推荐答案

watchOS 2 可以访问 CoreData、NSCoding 和 NSUserDefaults.取决于您要存储的数据,但这些是最好的(第一方)选项.

watchOS 2 has access to CoreData, NSCoding and NSUserDefaults. Depends on the data you want to store but those are the best (first party) options.

如果您打算使用 NSUserDefaults,请不要使用 standardUserDefaults,您应该使用 initWithSuiteName: 并传入您的应用程序组的名称.

If you are going to use NSUserDefaults, do not use standardUserDefaults you should use initWithSuiteName: and pass in the name of your app group.

您甚至可以在 NSUserDefaults 上创建一个类别/扩展名以简化此操作.

You could even make a category/extension on NSUserDefaults to make this easier.

@interface NSUserDefaults (AppGroup)
+ (instancetype)appGroupDefaults;
@end

@implementation NSUserDefaults (AppGroup)

+ (instancetype)appGroupDefaults {
    static NSUserDefaults *appGroupDefaults = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        appGroupDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"com.whatever.yourappgroupname"];
    });
    return appGroupDefaults;
}

@end

迅捷

private var _appGroupDefaults = NSUserDefaults(suiteName: "com.whatever.yourappgroupname")!

extension NSUserDefaults {
    public func appGroupDefaults() -> NSUserDefaults {
        return _appGroupDefaults
    }
}

这篇关于Watch OS 2 - 如何在 Watch 上为完全原生的应用程序存储数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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