I have created an outlet for a textview and I’m trying to use it in a function, outside of the function it works fine, inside its not declared. When I pass it along with the function like StartFunction(textBox) it works fine, but this function also has to work with a bunch of other things like this and I don’t like the idea of just passing everything with the function.
What would be a better alternative?
// Header File
- (IBAction)startButton_clicked:(id)sender;
@property (strong, nonatomic) IBOutlet UITextView *textBox;
// Main file
- (IBAction)startButton_clicked:(id)sender {
if (currentlyOn == false) StartFunction(headLabel);
else textBox.text = @"Already Started"; // Works fine here
}
void StartFunction(UILabel *_headLabel)
{
_headLabel.text = @"This works fine because it's passed with the function";
textBox.text = @"textBox is undeclared here";
}
It sounds like you need to use a method rather than a function for your situation.
A method is really a type of function which is silently passed a reference to an instance of itself, this is given the name
self. Using that reference the method can access instance variables, methods and properties. Uses ofselfare also often silently added for you.So, assuming your code is part of
myClassyour methodstartButton_clickedis approximately (we’re glossing over a few details) the same as the function:Note the extra argument and the use of
selfin the assignment. The method call:is approximately equivalent to:
which is where the silently passed
selfcomes from.Functions are not treated in this way at all, there is no hidden argument passed, and lacking that silent way to access instance variables, properties and methods.
Both methods and functions have their uses and you select based on the need. In your case it sounds like you need a method as you wish to access an instance.
HTH.