![](/img/trans.png)
[英]Is it possible to use a delegate to send a message when the event is not produced by a UIButton?
[英]In ObjectiveC using delegate how do I send a message without using a UIButton?
最近,我学会了使用委托在按下按钮时将消息从一个类发送到另一类,并且我想了解如何在不执行按钮操作的情况下发送消息。 苹果文档表明可能的方法是performSelector:(SEL)aSelector;
但是当我尝试使用它时却没有运气。 相反,这是我尝试过的。
在MicroTune.h中 ,我定义了一个委托并为其赋予了一个属性
@class Synth;
@protocol TuningDelegate <NSObject>
-(void)setTuning:(NSData *)tuningData;
@end
@interface MicroTune : NSObject
{
…
}
@property (assign) id<TuningDelegate> delegate;
@end
在Synth.h中 ,我声明了该类,因此它充当了委托
#import "MicroTune.h"
@interface Synth : NSObject <TuningDelegate>
在Synth.m中 ,我创建了一个方法让我知道消息已到达
#import "Synth.h"
- (void)setTuning:(NSData *)tuningData
{
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:tuningData];
NSLog(@" hip hip %@", array);
}
编辑
并且,同样在Synth.m中,为了确保能够识别出委托人,我添加了以下内容
- (id)initWithSampleRate:(float)sampleRate_
{ if ((self = [super init]))
{
microTuneClassObject.delegate = self;
// etc. etc.
} return self;
}
(Use of undeclared identifier 'microTuneClassObject')
并尝试了
MicroTune.delegate = self;
(Property 'delegate' not found on object of type 'MicroTune')
和
self.MicroTune.delegate = self;
(Property 'MicroTune' not found on object of type 'Synth *')
最后,在MicroTune.m中 ,我定义了一种发送消息的方法
#import "MicroTune.h"
- (void)sendTuning:(NSData *)tuningData
{
[synthLock lock];
[self.delegate setTuning:(NSData *)tuningData];
[synthLock unlock];
}
但是Xcode给出了以下消息。
No type or protocol named 'TuningDelegate'
有人可以请我解释发送消息需要做什么吗? 谢谢。
结论
解决方案可以在我的补充答案中找到。
在MicroTune.h
文件中,
代替#import "Synth.h"
编写@class Synth
在Synth.h中
@class MicroTune;
@interface Synth : NSObject
{
MicroTune *setTuning;
}
- (MicroTune*)setTuning;
在Synth.m中
#import "Synth.h"
#import "MicroTune.h"
从Synth.m,从MicroTune中检索调音数据(当PlayViewController发送MIDI程序更改消息时)
- (void)sendProgramChange:(uint8_t)oneOfFiveFamilies
onChannel:(uint8_t)oneOfSixteenPlayers
{
uint8_t tuningTransposition = oneOfFiveFamilies;
uint8_t assignedPitches = oneOfSixteenPlayers;
MicroTune *dekany = [[MicroTune alloc] init];
// send a 2-byte "MIDI event" to fetch archived tuning data
id archivedArray = [dekany sendMIDIEvent:(uint8_t)tuningTransposition
data1:(uint8_t)assignedPitches];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:archivedArray];
NSLog(@"\n%@", array);
for (int i = 0; i <10; i++)
{
NSNumber *num = array[i];
float hertz = [num floatValue];
_pitches[i] = hertz;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.