问题
I recently learned to use delegates to send messages from one class to another whenever a button is pressed and I'd like to find out how to send a message without a button action. Apple documentation suggests a likely method is performSelector:(SEL)aSelector;
but I had no luck when I tried to use it. Instead, this is what I tried.
In MicroTune.h, I defined a delegate and gave it a property
@class Synth;
@protocol TuningDelegate <NSObject>
-(void)setTuning:(NSData *)tuningData;
@end
@interface MicroTune : NSObject
{
…
}
@property (assign) id<TuningDelegate> delegate;
@end
In Synth.h, I declared the class so it acts as a delegate
#import "MicroTune.h"
@interface Synth : NSObject <TuningDelegate>
and in Synth.m, I created a method to let me know the message arrived
#import "Synth.h"
- (void)setTuning:(NSData *)tuningData
{
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:tuningData];
NSLog(@" hip hip %@", array);
}
EDIT
And, also in Synth.m, to make sure the delegate is recognised, I added the following
- (id)initWithSampleRate:(float)sampleRate_
{ if ((self = [super init]))
{
microTuneClassObject.delegate = self;
// etc. etc.
} return self;
}
(Use of undeclared identifier 'microTuneClassObject')
and also tried
MicroTune.delegate = self;
(Property 'delegate' not found on object of type 'MicroTune')
and
self.MicroTune.delegate = self;
(Property 'MicroTune' not found on object of type 'Synth *')
And finally, in MicroTune.m, I defined a method to send the message
#import "MicroTune.h"
- (void)sendTuning:(NSData *)tuningData
{
[synthLock lock];
[self.delegate setTuning:(NSData *)tuningData];
[synthLock unlock];
}
but Xcode gave the following message.
No type or protocol named 'TuningDelegate'
Can someone kindly explain what I need to do to send the message ? Thanks.
CONCLUSION
The solution can be found in my supplementary answer.
回答1:
In MicroTune.h
file,
instead of #import "Synth.h"
write @class Synth
回答2:
In Synth.h
@class MicroTune;
@interface Synth : NSObject
{
MicroTune *setTuning;
}
- (MicroTune*)setTuning;
In Synth.m
#import "Synth.h"
#import "MicroTune.h"
and from Synth.m, tuning data is retrieved from MicroTune (when the PlayViewController sends a MIDI Program Change message)
- (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;
}
}
来源:https://stackoverflow.com/questions/44969276/in-objectivec-using-delegate-how-do-i-send-a-message-without-using-a-uibutton