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

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

问题描述

我需要在WatchKit扩展程序-仅监视端上存储大约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天全站免登陆