我目前正在设置我的监视工具包,使用以下内容将数据从源传递到目标:
来源
- (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中的解决方案。
答案 0 :(得分:0)
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"];
}
}