Watchkit - 将数据传递给源控制器

Watchkit - passing data to source controller

我目前已将我的手表套件设置为使用以下方法将数据从源传递到目标:

来源

- (IBAction)changeRep {
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"rep", @"button", nil];
[self presentControllerWithName:@"KeyPadInterfaceController" context:dictionary];

}

目的地

- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];


_parent = [context valueForKey:@"button"];



}

我正在尝试使用以下方法将数据从目标视图获取到源视图,但未调用源视图中的 dataFromKeyPad。

Source.h

@interface WorkoutDetailInterfaceController : WKInterfaceController <KeyPadInterfaceControllerDelegate>{

Source.m

- (void)dataFromKeyPad:(NSDictionary *)data {
if ([data objectForKey:@"rep"]){
    _repNum = [data valueForKey:@"rep"];
    NSString *repTitle = [NSString stringWithFormat:NSLocalizedString(@"%@ reps", "Number of Reps"), _repNum];
    [self.reps setTitle:repTitle];
} else if ([data objectForKey:@"weight"]) {
    _weightNum = [data valueForKey:@"weight"];
    NSString *weightTitle = [NSString stringWithFormat:NSLocalizedString(@"%@ reps", "Number of Reps"), _weightNum];
    [self.reps setTitle:weightTitle];
}
}

Destination.h

@protocol KeyPadInterfaceControllerDelegate <NSObject>

- (void)dataFromKeyPad:(NSDictionary *)data;

@end

@property (nonatomic, weak) id<KeyPadInterfaceControllerDelegate> delegate;

Destination.m

- (IBAction)okAct{
NSDictionary *dictionary;

if ([_parent isEqualToString:@"rep"]) {
    dictionary  = [[NSDictionary alloc] initWithObjectsAndKeys:_result, @"rep", nil];
} else {
    dictionary =[[NSDictionary alloc] initWithObjectsAndKeys:_result, @"weight", nil];
}
[self.delegate dataFromKeyPad:dictionary];

[self dismissController];
}

当我按下 ok 按钮时,会调用 okAct,它会遍历所有内容,包括 dismissController 但 [self.delegate dataFromKeyPad:dictionary];不会在源视图中触发任何内容。有什么建议么?我需要 Objective C.

中的解决方案

Destination.m 的 self.delegate 中设置了什么值?它可能在 self.delegate.

中包含 nil

为了防止崩溃,您应该执行以下操作。

if ([self.delegate respondsToSelector:@selector(dataFromKeyPad:)])
{
    [self.delegate dataFromKeyPad:dictionary];
}

新增(7/29):设置方式self.delegate

来源

- (IBAction)changeRep {
    NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                                @"rep", @"button",
                                self, @"delegate",
                                nil];
    [self presentControllerWithName:@"KeyPadInterfaceController" context:dictionary];
}

目的地

- (void)awakeWithContext:(id)context
{
    [super awakeWithContext:context];

    // Configure interface objects here.
    if ([context isKindOfClass:[NSDictionary class]]) {
        self.delegate = [context objectForKey:@"delegate"];
    } 
}