I am coming from c++ and I am trying to create validator class for user inputs in text fields.
My function needs to return a bool
and a message (if bool
is YES message is NULL
). Is there in Objective-C something similar to std::pair
from C++ ( which contains pair of values)?
There is no std::pair
in Cocoa; you can create your own. However, a more idiomatic approach to the problem is similar to other methods that return errors, namely, passing a pointer to a pointer to an error, and returning BOOL
:
-(BOOL) validateInput:(id)input error:(NSError**)errPtr {
// Validate the input
// If the input is valid, do not assign `errPtr`, and return `YES`
// Otherwise, create a `NSError` object, and assign to errPtr
}
You can call this method as follows:
NSError *err;
if (![validator validateInput:@"some input" error:&err]) {
// Show the error
}
For an example of how this idiom is used in Cocoa, see the regularExpressionWithPattern:options:error:
method of the NSRegularExpression
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With