As I'm beginner with mobile/OO programming, I reached a situation that confused me and made me wonder if I was coding correctly...
The main class:
class ViewController: UIViewController, SoundAnalyserDelegate{
lazy var fontSize : SoundAnalyser = {
return SoundAnalyser(delegate: self)
}()
@IBOutlet var frequencyLabel: UILabel!
@IBOutlet var amplitudeLabel: UILabel!
@IBOutlet var note: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
soundAnalyser.start()
}
func setLabelAmp (_ text:String) {
frequencyLabel.text = text
}
func setLabelFreq (_ text:String) {
frequencyLabel.text = text
}
func setLabelNote (_ text:String) {
frequencyLabel.text = text
}
And the Second class:
class SoundAnalyser {
var delegate:SoundAnalyserDelegate?
let minimum = Double(160)
let maximum = Double(1400)
var mic: AKMicrophone
var tracker: AKFrequencyTracker
fileprivate var silence: AKBooster
fileprivate var timer: Timer?
fileprivate var notesArray: [(String, Double)]?
init(delegate: SoundAnalyserDelegate){
mic = AKMicrophone()
tracker = AKFrequencyTracker(mic, hopSize: minimum, peakCount: maximum)
silence = AKBooster(tracker, gain:0)
notesArray = self.getNotesFrequencies()
self.delegate = delegate
}
func tick(){
let amp = tracker.amplitude
let freq = tracker.frequency
if amp > 0.05 && freq > minimum && freq < maximum{
let readNote = notesArray![analyseCapturedSound()]
delegate?.setLabelAmp(String(format:"%f", amp)) //Setting the text of a label from the UI
delegate?.setLabelFreq(String(format:"%f", freq))
// delegate?.setLabelNote(String(format:"%f", readNote))
print("freq:", freq," amp:", amp," NOTE: \(readNote)")
}
}
I just included the most important code to express what I am trying to ask.
Summary: Class ViewController initiates SoundAnalyser. Under SoundAnalyser, there's a function that executes a function from ViewController ("delegate?.setLabel..."). I've made it with a delegate class using protocol, but I don't know why I feel that something is wrong.. I mean, executing a method of its creator... is it right? If not, what's the most 'good citizen' way to implement something with the same result?