我想知道如何使用委托从一个名为MotionListener的类向MotionListener发送时钟消息,但是很难将苹果对target-action的解释转换成一个可行的命令。
目标-动作是一种设计模式,在这种模式中,当事件发生时,对象保存向另一个对象发送消息所需的信息。存储的信息包括两项数据:一个动作选择器(它标识要调用的方法)和一个目标(它是接收消息的对象)。]1。
我在使用myButton的示例(下面)中使用委托向被按下的名为fromButtonInSubview的目标发送消息时,我没有遇到任何问题。
[mySyncButton addTarget:self.delegate
action:@selector(fromSyncButtonInSubview:)
forControlEvents:UIControlEventTouchUpInside];我假设,为了发送不来自UIButton,的信号,我仍然需要声明协议a,给它一个属性c,并包括初始化方法b。
一个
@protocol SyncDelegate <NSObject>
-(void)fromSync:(int)clock;
@end
@interface MotionListener : NSObject {
}B
- (id) initMotionSensingWith:(float)updateInterval;C
@property (assign) id<SyncDelegate> delegate;
@end并在接口d中声明协议,并在实现e中添加目标方法。
D
@interface PlayViewController : UIViewController <SyncDelegate>E
- (void)fromSync:(int)clock
{
NSLog(@"tick"); // do stuff and show
}然后在MyViewController,导入MotionListenerf中,在实现g中声明它并定义委托h
F
#import "MotionListener.h"G
MotionListener *sync = [[MotionListener alloc] initMotionSensingWith:(float)updateInterval];H
sync.delegate = self;但是,尽管重新阅读了上面引用的解释,在几次失败的尝试之后,我还没有编写一个命令,将同步信号从MotionListener发送到MyViewController.,我知道在UIButton示例(上面)中,它将产生addTarget:self.delegate和action:@selector(fromSync:)的效果。在任何人建议NSTimer selector,之前,我已经在50赫兹计时,而同步信号是1赫兹。
例如:
[NSTimer scheduledTimerWithTimeInterval:0.02; // 50 Hz
target:self
selector:@selector(motionRefresh:)
userInfo:nil
repeats:YES];
- (void)motionRefresh:(id)sender
{
count = (count + 1) % 50; // every 1 second
if (count == 0 )
{
// send the sync message here
// EDIT
NSLog(@"sending %i", count);
[self.delegate fromSync:(int)count];
}
}因此,我的问题是:使用委托,如何在每次count打开0时发送同步消息?答案可能是令人尴尬的简单,但我可以穿,如果你能帮忙。谢谢。
发布于 2017-08-12 08:05:36
我不确定我是否正确地理解了你的代码。但是,我认为您只需将您的// send the sync message here行替换为调用您的代表,比如[self.delegate fromSync:WHATEVERVALUEYOUWANTTOINFORMABOUT];。
https://stackoverflow.com/questions/45647941
复制相似问题