Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an object similar to std::pair in Objective-C?

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)?

like image 433
Damir Avatar asked Feb 09 '13 22:02

Damir


1 Answers

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.

like image 145
Sergey Kalinichenko Avatar answered Nov 02 '22 23:11

Sergey Kalinichenko