当事件不是由 UIButton 产生时,是否可以使用委托发送消息?

Is it possible to use a delegate to send a message when the event is not produced by a UIButton?

我想知道如何使用委托从名为 MotionListener 的 class 向 MyViewController 发送时钟消息,但在翻译 Apple 对 target-action 变成一个可行的命令。

Target-action is a design pattern in which an object holds the information necessary to send a message to another object when an event occurs. The stored information consists of two items of data: an action selector, which identifies the method to be invoked, and a target, which is the object to receive the message.]1

我在 (下)myButton 示例中应用解释 (上) 没有问题每当按下

时向名为 fromButtonInSubview 的目标发送消息
        [mySyncButton addTarget:self.delegate
                         action:@selector(fromSyncButtonInSubview:)
               forControlEvents:UIControlEventTouchUpInside];

我假设为了发送不是来自 UIButton, 的信号,我仍然需要声明协议 [a],给它a 属性 [c] 并包含一个初始化方法 [b]

[a]

    @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,中导入MotionListener[f],在实现中声明[g]并定义委托 [h]

[f]

    #import "MotionListener.h"

[g]

    MotionListener *sync = [[MotionListener alloc] initMotionSensingWith:(float)updateInterval];

[h]

    sync.delegate = self;

但是尽管重新阅读了上面引用的解释并在多次尝试失败后,我还没有编写一个命令来将同步信号从 MotionListener 发送到 MyViewController. 我知道它会有addTarget:self.delegateaction:@selector(fromSync:)UIButton 示例中的效果 (上文)。在有人建议 NSTimer selector, 之前,我已经将其时钟设为 50 Hz,而同步信号为 1 Hz

例如

     [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 时发送同步消息?答案可能简单得令人尴尬,但如果你能帮忙的话,我可以穿上它。谢谢。

我不确定我是否正确理解了您的代码。但我认为你只需要用 [self.delegate fromSync:WHATEVERVALUEYOUWANTTOINFORMABOUT];.

之类的对你的委托的调用来替换你的 // send the sync message here