如何观察NSUserDefault initWithSuiteName的键值,以便发送和可能从iOS App接收数据到WatchKit

时间:2015-05-03 18:46:02

标签: ios objective-c xcode swift nsuserdefaults

我正在尝试各种解决方案,以便将数据从iOS App发送/接收到WatchKit App。

尝试MMWormhole无效,所以尝试以下方法。

在ViewDidLoad中:

mySharedDefaults = [[NSUserDefaults alloc] initWithSuiteName: kGROUP_SUITE_NAME];

[mySharedDefaults addObserver:self forKeyPath:@"timeLeft" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:NULL];

-(void)observeValueForKeyPath:(NSString *)keyPath
                 ofObject:(id)object
                   change:(NSDictionary *)change
                  context:(void *)context
{
// NSLog requires a formatting string as its first arg
// NSLog(keyPath);
NSLog(@"observeValueForKeyPath: keyPath=%@", keyPath);
NSLog(@" object=%@", object);
NSLog(@" text=%@", [object valueForKey:keyPath]);
}

我在应用程序中调用它:

NSString *timeLeft = @"00:00";
    [mySharedDefaults setObject:timeLeft forKey:@"timeLeft"];

我找到了Swift的这个代码,Objective-C的等价是什么?

//写

let sharedDefaults = NSUserDefaults(suiteName: appGroupName)
sharedDefaults?.setInteger(1, forKey: "myIntKey")

//读

let sharedDefaults = NSUserDefaults(suiteName: appGroupName)
let myIntValue = sharedDefaults?.integerForKey("myIntKey")

我真的只想在写入时读取(即:观察值的变化)。

我添加了应用程序组(在iOS应用程序中),并确保它存在于目标(WatchKit应用程序)中

1 个答案:

答案 0 :(得分:-1)

您无法可靠地KVO共享用户默认值。请改用MMWormhole。 MMWormhole使用Darwin通知中心来提醒扩展和主应用之间的变化。