Question

I have my viewcontroller class for my only current View and another class with static methods for my mathematical logic. ViewController class has an IBOutlet for a label. How can I reference this outlet from within the functions of my Logic class?

Was it helpful?

Solution

You could pass a pointer to the logic class just like any other variable, but I wouldn't recommend directly accessing the IBOutlet property.

What I'd recommend, is either having the logic class return the values and have the controller update the label as needed, or if it involves background processing that doesn't return immediately, use the delegate pattern. This way, the logic class will inform the controller when the data is ready, or the calculations are finished, and then the controller can update the UI as needed.

Look into iOS Protocols to define the structure of a delegate class :)

OTHER TIPS

You shouldn't allow your Logic class to access a UI control because it does not follow the Model-View-Controller pattern, which is a smart way to keep your code organized so that it's easier to follow as your project becomes more complicated. Instead, you would want your ViewController to communicate between the UI and the Logic class for you.

For example, if you had a Calculate button at the bottom of your view that the user taps, the tap should be handled by the ViewController. The ViewController would call a function in your Logic class that might return a value. Then the ViewController would take that value and set it as the text of the label. Here's a snippet of code that illustrates the idea:

- (IBAction) calculateSomeValue: (id) sender {
    int result = [Logic calculateValue];
    [self.label setText: [NSString stringWithFormat: @"Your result is: %d", result]];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top